分类: LINUX
2012-01-04 16:27:35
用SSH登录远程主机,每次都输入密码挺麻烦的,其实可以用密钥文件来登录:
1. 用ssh-keygen命令生成private/public密钥对,提示问题都用默认回答即可。
$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/guoyong/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/guoyong/.ssh/id_rsa.
Your public key has been saved in /home/guoyong/.ssh/id_rsa.pub.
2. 用ssh-copy-id命令把公钥复制到远程主机上,user就是你登录用的用户名
$ ssh-copy-id -i /root/.ssh/id_rsa
3. 验证一下吧
$ ssh echo "it works"
例:三服务器A.B.C 假设A.C要互相访问需经过B,本实现A与C之间的互访。A.B.C密码分别为:PWDA.PWDB.PWDC。操作主机为A。
1.从A到C的自动SSH登陆。
#!/usr/bin/expect -f
set timeout 30
spawn ssh
expect "password:"
send "PWDB\r"
expect "]*"
send "ssh "
expect "password:"
send "PWDC"
interact
2.从A到C文件的SCP。
#!/usr/bin/expect -f
set timeout 300
set file [lindex $argv 0]
spawn scp $file
expect "password:"
send "PWDB\r"
expect "]*"
spawn ssh
expect "password:"
send "PWDB\r"
expect "]*"
send "scp $file "
expect "password:"
send "PWDC\r"
expect "]*"
exit
interact
3.从C到A文件的SCP。
#!/usr/bin/expect -f
set timeout 300
set file [lindex $argv 0]
spawn ssh
expect "password:"
send "PWDB\r"
expect "]*"
send "scp ./\r"
expect "password:"
send "PWDC\r"
expect "]*"
send "exit\r"
expect "]*"
spawn scp ./
expect "password:"
send "PWDB\r"
interact