当前位置: 代码迷 >> 综合 >> 通过SSH命令在远程服务器上执行脚本或命令
  详细解决方案

通过SSH命令在远程服务器上执行脚本或命令

热度:78   发布时间:2024-01-29 15:53:03.0

通过SSH命令在远程服务器上执行脚本或命令,需要在本脚本所在机器安装expect软件

#!/usr/bin/expect
# 文件名 : executeSshCommand.sh
# 作  者 : Lotomer
# 时  间 : 2017-08-26
# 功  能 : 执行远程命令ssh
# 版  本 : 1.1
# 参  数 :
#           1) remote_ip        : 必填,远程服务器IP
#           2) remote_user      : 必填,远程服务器用户
#           3) remote_password  : 必填,远程服务器用户密码
#           4) remote_command   : 必填,需要在远程服务器执行的命令
#           5) remote_password2 : 必填,远程服务器用户备用密码
#           6) timeout          : 可选,连接超时,单位:秒,默认不超时
# 示  例 : ./executeSshCommand.sh 192.168.1.3 root 123456 "cat /proc/cpuinfo" 654321 10
# ----------------------------------------
# 版本号   更新时间    更新说明
#  1.0     2017-08-26  初版
#  1.1     2019-11-16  增加返回值
# ----------------------------------------
#set timeout 5set host [lindex $argv 0]
set user [lindex $argv 1]
set pwd [lindex $argv 2]
set sshCommand [lindex $argv 3]
set pwd2 [lindex $argv 4]
set timeout [lindex $argv 5]
if {$timeout == ""} {#puts "timeout is empty, use -1"set timeout -1
} else {#puts "timeout is $timeout"set timeout $timeout
}spawn ssh  $user@$host "$sshCommand"
expect {"*yes/no*" {send "yes\r";exp_continue}"*assword" {send "$pwd\r";set pwd [exec echo $pwd2];exp_continue}"]#" { send "$sshCommand\r";exp_continue }eof
}#puts $expect_out(buffer)
lassign [wait] pid spawnid os_error_flag value
# 系统错误
if {$os_error_flag == -1} {puts "os errno: $value"
} else {# 返回 CMD 执行结果exit $value
}

 

  相关解决方案