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” “命令”

【注】多个命令用;分开。

你可能感兴趣的:(linux)