Although the ninja from Iga and Koga were espionage mercenaries, in other parts of Japan the ninja took on other roles. Many daimyo had elite groups of ninja who served him as loyally as any samurai. They served as spies, scouts, or commando groups that would make guerilla attacks on enemy castles and encampments. When an army retreated from the field of battle, ninja with firearms were left lying in hiding to attack the oncoming enemy soldiers.
Ninja were particularly useful when a castle was under siege. In such circumstances, the ninja were often the only people who could sneak out of the castle. In one case, a ninja left the castle at night, entered the enemy camp, and stole their flag. The next morning, the enemy's army awoke to find their own flag waving mockingly in the breeze from the castle wall. The moral victory accomplished by humiliating their enemies in this way could be very important for the residents of a castle who were waiting out a long siege.
One of the primary roles of the ninja, and the one for which they are most well known and feared, was that of assassin. The daimyo of feudal Japan came to fear assassination at the hands of ninja so much that they spent a great deal of time at "secret springs," which were hidden resorts built around natural springs far from the daimyo's castle.
Within the castle, a daimyo would often go to extraordinary lengths to protect himself from ninja. In Kyoto, the Nijo castle sported "nightingale floors." These carefully crafted wooden floors were counterbalanced so that anyone walking on them made a loud squeaking noise. Some daimyo even kept guards in the same room with them at all times, even when they were asleep. The Tokugawa family required everyone in their household to wear trousers with wide legs that dragged on the floor, making it impossible to walk quietly.
During the Tokugawa (or Edo) period, Japan's civil wars were halted by the strict controls of the Tokugawa shogun. Peacetime forced many people in Japanese society to find different roles, including the ninja. They were very useful to Tokugawa, acting as spies and bodyguards in the enforcement of the laws that allowed him to maintain control of the clans.