shell常用脚本

登录服务器

vim login.sh

#!/usr/bin/expect
set password "密码"
set host ip
spawn ssh root@$host
expect {
         "*yes/no" { send "yes\r"; exp_continue}
         "*password:" { send "$password\r" }
}
interact

chmod a+x login.sh
自动登录脚本

#!/bin/bash

#Description: auto login the remote server 
#Author:majinxu 
#Version:1.0 
#CreateTime:2018-3-012 18:34:41

user="zhangsan"
passwd="123456"

host_list=( "st1.qa.bj2.yongche.com" 
"st2.qa.bj2.yongche.com"
"st3.qa.bj2.yongche.com"
)

#seletc the host
select host in ${host_list[@]};
do
break
done

#execute the ssh action
expect -c "
spawn ssh $user@$host
expect {
\"yes\/no\" { send \"yes\n\"; exp_continue}
\"password:\" { send \"$passwd\n\" }
}
interact 
"

解释:

expect -c : -c参数跟字符串
spawn ssh $user@$host 连接服务器
expect {
\"yes\/no\" { send \"yes\n\"; exp_continue}
\"password:\" { send \"$passwd\n\" }
}
输入并接收用户名密码
是
"yes/no" { send "yes\n"; exp_continue}
"password:" { send "$passwd\n" }
} 转义后的结果
interact 
执行完成后保持交互状态,把控制权交给控制台

scp脚本

#!/bin/bash

file_source=$1
file_target=$2
pass=$3
if [[ -z "$file_source" ]]; then
    echo "usage :\${1} <file_source: user@ip:/root>"
    exit -1
fi
if [[ -z "$file_target" ]]; then
    echo "usage :\${2} <file_target: user@ip:/root>"
    exit -1
fi
if [[ -z "$pass" ]]; then
    echo "usage :\${3} <pass: 123456>"
    exit -1
fi
expect -c "
spawn bash -c  \"scp ${file_source} ${file_target}\"
expect {
\"*(yes\/no)?\" { send \"yes\n\"; exp_continue}
\"*password\" { send \"${pass}\n\" }
}
expect eof
"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容