The first method uses expect.
The script is as follows:
#! /usr/bin/expect -f
spawn scp 1 [email protected]:
expect "*password:"
send "your password\r"
expect eof
Of course, not only scp, other commands can also be automated with expect
Loop processing:
spawn scp 1 [email protected]:
for { set i 1 } {$i<500} {incr i} {
expect {"*password:" {send "koven\r"}
"*(yes/no)*" {send "yes\r"}
}
}
Note the spaces between the curly brackets.
The second method, using a key file.
Here it is assumed that host A (192.168.100.3) is used to obtain the files of host B (192.168.100.4).
Execute the following command on host A to generate a pairing key:
ssh-keygen -t rsa
When prompted, press Enter to default, and the public key is stored in the .ssh directory under the user directory. For example, root is stored in:
/root/.ssh/id_rsa.pub
Copy the id_rsa.pub file in the .ssh directory to the ~/.ssh/ directory of host B and rename it to authorized_keys,
Execute commands in host A to establish trust with host B, for example (assuming the IP of host B is: 192.168.100.4):
scp ~/.ssh/id_rsa.pub 192.168.100.4:/root/.ssh/authorized_keys
Now you can use the scp and ssh commands to get the files of host B without a password.
ssh 192.168.100.4 press Enter and no password is required.
Note: In fact, the content of id_rsa.pub is added to the authorized_keys of the other machine.
-----------------------------------------------------------------------------------------------------
#!/usr/bin/expect -f
set password 密码
spawn scp 用户名@目标机器ip:拷贝文件的路径 存放本地文件的路径
set timeout 300
expect "用户名@目标机器ip's password:" #注意:这里的“用户名@目标机器ip” 跟上面的一致
set timeout 300
send "$password\r"
set timeout 300
send "exit\r"
expect eof
附:scp参数
-r:拷贝目录
-c:允许压缩
一个完整的例子
#!/usr/bin/expect -f
set password 123456
#download
spawn scp [email protected]:/root/a.wmv /home/yangyz/
set timeout 300
expect "[email protected]'s password:"
set timeout 300
send "$password\r"
set timeout 300
send "exit\r"
expect eof
#upload
spawn scp /home/yangyz/abc.sql [email protected]:/root/test.sql
set timeout 300
expect "[email protected]'s password:"
set timeout 300
send "$password\r"
set timeout 300
send "exit\r"
expect eof
########
PS:需要先安装expect