如何以root身份远程运行命令?

时间:2016-02-05 06:32:25

标签: linux expect

我尝试以userA身份登录服务器,然后切换到root帐户并运行一些命令。步骤应该是:

  1. ssh userA@10.0.0.1
  2. su - root
  3. WHOAMI
  4. 我使用下面的代码实施了第1步,但不知道如何实施第2步和第3步。

    #!/usr/bin/expect -f
    set timeout 12
    set password_root 12345678
    set password_A 12345678
    
    spawn ssh -t sflow@10.0.0.1
    expect -re ".*password:"
    send "$password_sflow\r"
    expect eof
    

1 个答案:

答案 0 :(得分:1)

#!/usr/bin/expect
set timeout 12
set password_root 12345678
set password_A 12345678

set prompt "#|>|\\\$ $"
spawn ssh -t user1@xxx.xxx.x.xx
expect  {
        timeout {puts TIMEOUT}
        "yes/no" {send "yes\r";exp_continue}
        "password:" {send "user1password\r";exp_continue}
        -re $prompt
}
send "su - root\r"
expect "Password:"
send "rootpassword\r"
expect -re $prompt
send "whoami\r"
expect -re $prompt

# and to exit
send "exit\r"      ;# exit su
expect -re $prompt
send "exit\r"      ;# exit ssh
expect eof