【Linux学习笔记】Linux主机如何实现无需输入密码的远程登录或脚本远程执行

来源:互联网 发布:me352ll a支持什么网络 编辑:程序博客网 时间:2024/06/05 14:27
        linux机器日常运维过程中,经常需要在本地运行脚本执行针对远程主机的命令。正常情况下,ssh登陆远程机器时会提示输入密码,这会影响到脚本的自动执行,(因为shell脚本中没有自动填充密码的命令)。
        总的来说,有两个办法来解决问题:
           1)建立主机间的ssh信任关系
           2)用python脚本模拟scp命令的密码输入过程,避免每次手工输密码。
        本文依次进行介绍。

1. 建立主机间的ssh信任关系实现不输入密码的登录
        假设需要建立从usr1@localhost到usr2@remote这两对(主机, 用户)间的信任关系,可以分为3步:
        1)生成usr1@localhost的authentication key

[usr1@localhost~]$ ssh-keygen -t rsaGenerating 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已经被追加到文件末尾。
        特别需要注意的是,上面执行的命令中,向usr2@remote的~/.ssh/authorized_keys写内容时,用的是>>做追加,而非>覆盖写,后者可能会清除掉remote主机之前已经与其它主机建立的信任关系。
        为避免手工输入命令出错,我们可以借助ssh-copy-id这个工具完成本步,而非人工修改authorized_keys文件,具体用法可参考这篇文章。但我机器上貌似没有ssh-copy-id这个命令。囧
        3)登陆验证
        经过前面两步,usr2@remote已经将usr1@localhost加入信任关系列表,因此,从usr1@localhost登陆usr2@remote时,就不需要密码了。
        至此,大功告成,shell脚本可以全自动执行了。
        小技巧:为避免每次建立主机间的信任关系时都输入几条命令,可以把上面的命令写成.sh脚本,需要建立信任关系时,在作为client的主机中直接执行脚本即可,会方便不少,且不易出错。

2. 通过python脚本实现scp自动密码输入
         借助pexpect module,实现scp密码输入过程的模拟。关于pexpect模块的介绍,可参考python官网介绍,可点击这里查看。
         pexpect的用法较为简单,这里贴一段代码,实际应用中,根据需要修改即可。
  

#!/bin/env python#-*- encoding: utf-8 -*-import pexpectdef 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 -1def main():    ip = '127.0.0.1'    user = 'test'    passwd = 'test@passwd'    cmd = 'df -h'    remote_ssh(ip, user, passwd, cmd)if __name__  == '__main__':    main()
【参考资料】
1. SSH login without password 
2. 3 Steps to Perform SSH Login Without Password Using ssh-keygen & ssh-copy-id 
3. Pexpect通过SSH执行远程命令 


============= EOF =============