Bash 生成和执行命令的脚本

Bash script to spawn and execute commands

我正在尝试创建一个 bash 脚本以通过 ssh 进入会话,然后 运行 命令退出会话。目前这是我目前所拥有的:

#!/usr/bin/expect -f

spawn ssh root@sc
expect "assword:"
send "password\r"
expect "#"
send "cd /data2/someDirectory\r"------> don't see this command being executed

和输出

[user@San ddb]$ test1
spawn ssh root@sc
root@sc's password:
SC02 RH 7.3 (0000009B 02.11.0.1)
[root@sc /]# [user@san1 ddb]$
[user@san1 ddb]$

所以我的问题是为什么目录没有设置为 myDirectory 而它只是退出会话?

您的 expect 脚本正在执行您想要的操作,但一旦作业 send 完成就会退出。

在脚本末尾设置一些 "expectation",例如 expect "$",然后尝试。

#!/usr/bin/expect -f

spawn ssh root@10.200.2.19
expect "assword:"
send "pass\r"
expect "#"
send  "\r"
send  "pwd\r"
send  "\r"
send  "cd /tmp\r"
send  "touch dummy\r"
expect "$"

你不需要为此期待:

ssh root@host 'cd /tmp; touch afile'

对于无密码操作,设置 ssh 密钥。这是一个不错的教程:http://support.suso.com/supki/SSH_Tutorial_for_Linux