Babies are bacteria-free at birth. The meconium (the first stool) contains no bacteria if secured early enough.
Meconium is a sterile mucilaginous material that accumulates in the fetal intestine and is expelled soon after birth. It contains secretions of intestinal glands, gut constituents (proteins, bile acids, fatty acids, and steroids), and components of amniotic fluid and vernix caseosa.
Bacterial colonization of infants begins at birth - literally. They pick up bacteria from the mother's vaginal canal in passing, which they swallow. This is not seen in infants delivered by C-section. The importance of colonization picked up through normal birth is such, that some hospitals are swabbing the vagina of mothers delivering by CS and colonizing the oropharynx that way. Breast-milk also contains lactobacilli and bifidobacteria that probably contribute to the initial establishment of the gut flora of newborns.
And, yes, an infection the mother has while delivering must be taken into account. Herpes and Group B strep are both dangerous for a neonate.
The first microbes to colonize the intestines of newborn babies are the aerobic bacteria Escherichia coli and Streptococci. Later, the gut is colonized with anaerobic bacteria, e.g. Bacteroides, Bifidobacteria, and Clostridia. In 1–2 y, the gastrointestinal tract of infants has developed a natural microflora, which resembles the microflora of adults.
The infant continues to pick up bacteria from all people they come into regular contact with, including nurses.
The effect of the maternal flora on the initial gut colonization may be less than expected as the fecal flora of infants started to resemble both the fecal flora of the mother as well as that of the first nurse.
Breast milk may contain bacteria which colonizes the gut as well
Infants aren't overwhelmed by infection due to the presence of antimicrobial peptides found on their skin, GI tract, and immunity is conferred via breast milk.
Several AMP have been characterized in vernix and skin of the newborn, indicating a well-developed innate immune system, which may play a pivotal role at the time of postnatal colonization.
Antimicrobial Components of the Neonatal Gut Affected Upon Colonization
Dynamics of gut colonization and source of intestinal flora in healthy newborn infants
Protection of the Neonate by the Innate Immune System of Developing Gut and of Human Milk
Establishment and development of lactic acid bacteria and bifidobacteria microbiota in breast-milk and the infant gut