• 使用paramiko远程登录并执行命令脚本


    #!/usr/bin/env python
    #coding=utf-8
    
    import paramiko, getpass,sys,traceback
    
    class ssh_utils():
        def login_by_passwd(self, ip, port, username, passwd):
            self.ip = ip
            self.port = port
            self.username = username
            self.passwd = passwd
            self.pkey = None
        
        def login_by_key(self, username, key_path, passwd):
            try:
                self.pkey=paramiko.RSAKey.from_private_key_file(key_path)
            except paramiko.PasswordRequiredException:
                if not passwd:
                    passwd = getpass.getpass('RSA key password: ')
                self.pkey = paramiko.RSAKey.from_private_key_file(key_path, passwd) 
             
        def ssh(self,shell):
            try:
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                if self.pkey:
                    ssh.connect(self.ip, self.port, self.username, compress = True, pkey= self.pkey)
                else:
                    if not self.passwd:
                        self.passwd = getpass.getpass('input password: ')
                    ssh.connect(self.ip,self.port,self.username, self.passwd)
                stdin, stdout, stderr = ssh.exec_command(shell)
                res = stdout.readlines()
                ssh.close()
                return res
            except:
                type, value, tb = sys.exc_info()
                return traceback.format_exception(type, value, tb)
            
        def scp(self,localpath,remotepath):
            try:
                t = paramiko.Transport((self.ip,self.port))
                if self.pkey:
                    t.connect(self.ip, self.port, self.username, pkey= self.pkey)
                else:
                    if not self.passwd:
                        self.passwd = getpass.getpass('input password: ')
                    t.connect(username = self.username, password = self.passwd)
                sftp = paramiko.SFTPClient.from_transport(t)
                sftp.put(localpath,remotepath)
                t.close()
                return "SCP OK"
            except:
                type, value, tb = sys.exc_info()
                return traceback.format_exception(type, value, tb)
    
    if __name__ == '__main__':
        #使用例子
        myssh = ssh_utils()
        myssh.login_by_passwd("23.83.25.18",222,"root","xiaoming.n5")
        ret = myssh.scp('/etc/fstab', '/tmp/')
        myssh.ssh("cd /tmp/ && tar -zcf fstab.tgz fstab")
  • 相关阅读:
    SQL随记(四)
    一些有用的方法命令
    导航目录
    HTML中       等6种空白空格的区别
    MyBatis学习资料
    Spring Cloud资料
    聚类算法对比
    Spark 读取HBase数据
    ZooKeeper设置ACL权限控制
    大数据工具选择
  • 原文地址:https://www.cnblogs.com/xiaoming279/p/6404289.html
Copyright © 2020-2023  润新知