1. 首选是往authorized_keys里追加公钥来实现
2. 第二种选择是使用expect来自动填充密码
3. 第三种是使用echo打印密码,然后自动手动复制粘贴
## 二、使用expect来自动填充密码
1)安装expect
sudo apt install expect # Ubuntu/Debian
sudo yum install expect # Centos/RedHat
2)创建.exp文件:vi .ssh_server.exp
#!/usr/bin/expect -f
set user [ lindex $argv 0 ]
set host [ lindex $argv 1 ]
set passwd [ lindex $argv 2 ]
set project [ lindex $argv 3 ]
set port [ lindex $argv 4 ]
spawn ssh -p $port $user@$host
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
expect "$ "
send "cd coding/$project \r"
interact
3)添加可执行权限:chmod +x .ssh_server.exp
4)创建另一个.exp文件:vi .scp_to_server.exp
#!/usr/bin/expect -f
set user [ lindex $argv 0 ]
set host [ lindex $argv 1 ]
set passwd [ lindex $argv 2 ]
set file_or_folder [ lindex $argv 3 ]
set port [ lindex $argv 4 ]
spawn scp -r -P $port $file_or_folder $user@$host:~
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
expect EOF
5) 添加可执行权限:chmod +x .scp_to_server.exp
6)创建scp+ssh多功能脚本:vi to_my_server.sh
#!/usr/bin/bash
user="username"
host="ip-or-domain"
passwd="password"
project="my-project"
port=22
if [ $1 ] then;
./.scp_to_server.exp $user $host $passwd $1 $port
else
./.ssh_server.exp $user $host $passwd $project $port
fi
7)添加可执行权限:chmod +x to_my_server.sh
## 后记@2023-12-06
脚本整合进了github中公开的carstino库:git clone git@github.com:waketzheng/carstino.git
克隆到本地后,修改里面的to_my_server.sh脚本,就可以一键ssh和scp了。