1. 建立主机间的ssh信任关系实现不输入密码的登录
假设需要建立从usr1@localhost到usr2@remote这两对(主机, 用户)间的信任关系,可以分为3步:
1)生成usr1@localhost的authentication key
[usr1@localhost~]$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/usr1/.ssh/id_rsa): [直接回车即可] Enter passphrase (empty for no passphrase): [若要建立无密码的ssh信任关系,这里直接回车!否则建立信任关系后,每次登陆远程机器均要求输入该密码] Enter same passphrase again: [直接回车] Your identification has been saved in /home/usr1/.ssh/id_rsa. Your public key has been saved in /home/usr1/.ssh/id_rsa.pub. The key fingerprint is: b4:de:66:2c:c1:04:ad:7c:48:7c:f7:94:71:09:85:21 usr1@localhost
执行完这步后,在localhost主机的~/.ssh目录下,可以看到id_rsa和id_rsa.pub两个文件,后者的内容就是后面要用到的public
authentication key。
需要说明的是,我们在这里通过-t rsa指定了加密算法是RSA,其实还有其它加密算法,具体可man ssh-keygen进行查看。
2)将上面生成的id_rsa.pub文件拷贝至usr2@remote的~/.ssh/authorized_keys文件中
[usr1@localhost~]$ cat ~/.ssh/id_rsa.pub | ssh usr2@remote 'cat >> .ssh/authorized_keys' usr2@remote's password: [这里输入usr2@remote主机的登陆密码]执行完这步后,查看usr2@remote的~/.ssh/authorized_keys文件,可以看到,usr1@localhost的public key已经被追加到文件末尾。
2. 通过python脚本实现scp自动密码输入
借助pexpect module,实现scp密码输入过程的模拟。关于pexpect模块的介绍,可参考python官网介绍,可点击这里查看。
pexpect的用法较为简单,这里贴一段代码,实际应用中,根据需要修改即可。
#!/bin/env python #-*- encoding: utf-8 -*- import pexpect def remote_ssh(remote_ip, user, passwd, cmd): try: remote_cmd = "ssh %s@%s '%s'" % (user, remote_ip, cmd) try: child = pexpect.spawn(remote_cmd) reply = ['password: ', 'continue connecting (yes/no)?'] idx = child.expect(reply) if 0 == idx: child.sendline(passwd) elif 1 == idx: child.sendline('yes') except pexpect.EOF: child.close() return 0 else: resp = child.read() child.expect(pexpect.EOF) child.close() print resp return 0 except Exception, e: print 'execute remote cmd failed, remote_ip=%s, user=%s, cmd=%s, errmsg=%s' % (remote_ip, user, cmd, e) return -1 def main(): ip = '127.0.0.1' user = 'test' passwd = 'test@passwd' cmd = 'df -h' remote_ssh(ip, user, passwd, cmd) if __name__ == '__main__': main()【参考资料】
============= EOF =============