我有下面的shell
脚本,其中我登录到特定的机器,现在我必须在登录后执行一个命令,该命令将启动/停止/特定进程的状态。
#!/usr/bin/expect -f
spawn ssh root@hostname
expect "Password:"
send "password123\r"
interact # here it is successfully login into machine,
sleep 2
/sbin/service heartbeat status # I want to execute this command
我怎样才能做到这一点?
答案1
您可以使用
ssh user@hostname "command"
这将打开 ssh 连接并运行命令。如有必要,系统将提示您输入密码。
如果您想自动执行此操作(不想每次都输入密码),您应该使用 ssh-pub-key 启用登录。
答案2
一旦生成交互式ssh
实例,它就会接管当前bash
实例,并且直到它完成执行后才会执行以下命令。
user@user-X550CL ~ % ssh user@localhost; echo string
user@localhost's password:
Welcome to Ubuntu 15.04 (GNU/Linux 3.19.0-15-generic x86_64)
* Documentation: https://help.ubuntu.com/
Last login: Tue Sep 15 09:10:01 2015 from localhost
user@user-X550CL ~ % exit
Connection to localhost closed.
string
有多种方法可以解决这个问题;
- 将命令作为参数传递:
spawn ssh root@hostname /sbin/service heartbeat status
user@user-X550CL ~/tmp % ssh user@localhost echo command1
user@localhost's password:
command1
user@user-X550CL ~/tmp % ssh user@localhost 'echo command1; echo command2; echo command3'
user@localhost's password:
command1
command2
command3
user@user-X550CL ~/tmp %
- 将命令分组到另一个脚本中,并使用
stdin
重定向传递该脚本:
user@user-X550CL ~/tmp % ssh user@localhost <script.sh
Pseudo-terminal will not be allocated because stdin is not a terminal.
user@localhost's password:
Welcome to Ubuntu 15.04 (GNU/Linux 3.19.0-15-generic x86_64)
* Documentation: https://help.ubuntu.com/
command1
command2
command3
user@user-X550CL ~/tmp %