在Ubuntu系統中,使用Telnet可以通過自定義腳本來自動化執行一系列命令。以下是實現這一目標的步驟:
安裝Expect:
sudo apt-get update
sudo apt-get install expect
編寫Expect腳本:
創建一個新的Expect腳本文件,例如telnet_script.exp
,并添加以下內容:
#!/usr/bin/expect -f
set timeout 20
set host "your_host_address"
set user "your_username"
set password "your_password"
spawn telnet $host
expect "login: "
send "$user\r"
expect "Password: "
send "$password\r"
# 發送自定義命令
send "your_custom_command\r"
expect "prompt_for_next_command: "
# 發送更多命令
send "another_command\r"
expect eof
賦予腳本執行權限:
chmod +x telnet_script.exp
運行腳本:
./telnet_script.exp
如果你更喜歡使用Python,可以使用pexpect
庫來實現類似的功能。
安裝pexpect:
sudo apt-get update
sudo apt-get install python3-pexpect
編寫Python腳本:
創建一個新的Python腳本文件,例如telnet_script.py
,并添加以下內容:
import pexpect
host = "your_host_address"
user = "your_username"
password = "your_password"
custom_command = "your_custom_command"
child = pexpect.spawn(f"telnet {host}")
child.expect("login: ")
child.sendline(user)
child.expect("Password: ")
child.sendline(password)
# 發送自定義命令
child.sendline(custom_command)
child.expect("prompt_for_next_command: ")
# 發送更多命令
child.sendline("another_command")
child.expect(pexpect.EOF)
print(child.before.decode())
運行腳本:
python3 telnet_script.py
timeout
值,以避免腳本長時間等待響應。通過以上方法,你可以在Ubuntu系統中使用自定義腳本來自動化Telnet會話。