1. 程式人生 > >Linux遠端拷貝&遠端執行命令shell指令碼

Linux遠端拷貝&遠端執行命令shell指令碼

很多時候linux伺服器管理、釋出程式碼等,通常需要兩個工具,一個是遠端拷貝,一個是遠端執行命令,下面介紹兩個比較好用的指令碼,實現這兩個功能。

需要安裝expect,遠端執行命令,centos下直接yum -y install expect,不能yum安裝下載原始碼安裝。

1、遠端拷貝指令碼(remote-cp.sh)

可以通過指令碼批量進行檔案遠端拷貝,或者在其他指令碼中使用,具體指令碼如下:

#!/usr/bin/expect -f
set ipaddress [lindex $argv 0]
set port [lindex $argv 1]
set username [lindex $

argv 2]
set passwd [lindex $argv 3]
set file [lindex $argv 4]
set pwd [lindex $argv 5]
set timeout 600

spawn scp $file $ipaddress:$pwd
expect {
“yes/no” { send “yes\r”;
exp_continue }
“assword:” { send “$passwd\r” }
}
expect eof

執行命令:./remote-cp.sh “ip” “port” “username” “password” “待拷貝檔案路徑” “遠端伺服器路徑”

2、遠端執行命令指令碼(remote-exe.sh)

可以通過指令碼實現遠端執行命令,對遠端伺服器進行管理,在程式碼釋出方面比較好用,具體指令碼如下:

#!/usr/bin/expect -f
set ipaddress [lindex $argv 0]
set port [lindex $argv 1]
set username [lindex $argv 2]
set passwd [lindex $argv 3]
set cmd [lindex\ $argv 4]
set timeout 600

spawn ssh $ipaddress -p$port -l$username
expect {
“yes/no” { send “yes\r”;
exp_continue }
“assword:” { send “$

passwd\r” }
}

expect -re “~]($|#)”
send “$cmd \r”

expect -re “~]($|#)”
send “exit\r”

執行命令:./remote-exe.sh “ip” “port” “username” “password” “命令”

【注】多個命令用;分開。