
spawn Command in Linux
The spawn command in Linux is primarily associated with the Expect scripting language, which is used to automate interactions with programs that require user input.
The spawn command is used to start or initiate a process or program within an Expect script, allowing the script to interact with the spawned program by sending commands and reading its output. This particular feature makes it particularly useful for tasks such as automating SSH login, FTP connections, and command-line tools that require real-time responses.
Table of Contents
Here is a comprehensive guide to the options available with the spawn command −
Syntax for the spawn Command
The basic syntax for the spawn command in an Expect script is −
spawn [program] [arguments]
- [program] − The name of the program or command you want to initiate.
- [arguments] − Optional arguments passed to the program.
Examples of the spawn Command in Linux
Below are some hands-on examples of how to use the spawn command in a Linux environment −
- Automating SSH Login
- Automating File Transfer with FTP
- Running a Shell Command
- Simulating User Input
Automating SSH Login
To automate an SSH connection using spawn, you can write an Expect script like this −
spawn ssh user@host expect "password:" send "mypassword\r" interact
Here,
- The spawn ssh user@host starts the SSH connection.
- The expect command waits for the prompt asking for a password.
- The send command provides the password.
- interact allows control to be handed back to the user.
Automating File Transfer with FTP
To automate an FTP session, you can use the spawn command in a script like this −
spawn ftp myftpserver.com expect "Name:" send "myusername\r" expect "Password:" send "mypassword\r" expect "ftp>" send "put myfile.txt\r" expect "ftp>" send "bye\r"
Here,
- The spawn ftp myftpserver.com initiates the FTP session.
- It automates the login process and uploads the file myfile.txt using commands like put.
Running a Shell Command
You can use spawn to execute a shell command and interact with its output. For example −
spawn ls -l expect "$" interact
Where,
- spawn ls -l runs the ls -l command.
- The script interacts with the terminal output after the command executes.
Simulating User Input
Suppose you have a program that prompts for user input. You can automate responses using spawn −
spawn myprogram expect "Enter your name:" send "Awais\r" expect "Enter your age:" send "25\r" expect "Thank you"
Here, the script interacts with myprogram by sending predefined responses when prompted.
Conclusion
The spawn command is a useful tool for automating interactive operations, especially in conjunction with the Expect scripting language. Whether you are handling SSH logins, FTP connections, or automating interactive program input, spawn makes repetitive operations easy. Its versatility makes it ideal for system administrators and developers who would rather automate operations and increase productivity.