paramiko模块(基于SSH用于连接远程服务器)

paramiko模块,基于SSH用于连接远程服务器并执行相关操作

class SSHConnection(object):
    def __init__(self, host_dict):
        self.host = host_dict['host']
        self.port = host_dict['port']
        self.username = host_dict['username']
        self.pwd = host_dict['pwd']
        self.__k = None
 
    def connect(self):
        transport = paramiko.Transport((self.host,self.port))
        transport.connect(username=self.username,password=self.pwd)
        self.__transport = transport
 
    def close(self):
        self.__transport.close()
 
    def run_cmd(self, command):
        """
         执行shell命令,返回字典
         return {'color': 'red','res':error}或
         return {'color': 'green', 'res':res}
        :param command:
        :return:
        """
        ssh = paramiko.SSHClient()
        ssh._transport = self.__transport
        # 执行命令
        stdin, stdout, stderr = ssh.exec_command(command)
        # 获取命令结果
        res = unicode_utils.to_str(stdout.read())
        # 获取错误信息
        error = unicode_utils.to_str(stderr.read())
        # 如果有错误信息,返回error
        # 否则返回res
        if error.strip():
            return {'color':'red','res':error}
        else:
            return {'color': 'green', 'res':res}
 
    def upload(self,local_path, target_path):
        # 连接,上传
        sftp = paramiko.SFTPClient.from_transport(self.__transport)
        # 将location.py 上传至服务器 /tmp/test.py
        sftp.put(local_path, target_path, confirm=True)
        # print(os.stat(local_path).st_mode)
        # 增加权限
        # sftp.chmod(target_path, os.stat(local_path).st_mode)
        sftp.chmod(target_path, 0o755)  # 注意这里的权限是八进制的,八进制需要使用0o作为前缀
 
    def download(self,target_path, local_path):
        # 连接,下载
        sftp = paramiko.SFTPClient.from_transport(self.__transport)
        # 将location.py 下载至服务器 /tmp/test.py
        sftp.get(target_path, local_path)
 
    # 销毁
    def __del__(self):
        self.close()
 
  
#unicode_utils.py
def to_str(bytes_or_str):
    """
    把byte类型转换为str
    :param bytes_or_str:
    :return:
    """
    if isinstance(bytes_or_str, bytes):
        value = bytes_or_str.decode('utf-8')
    else:
        value = bytes_or_str
    return value

 

# -*- coding: utf-8 -*

import paramiko, getpass  # getpass是隐藏密码

def ssh_connect(cmd, host_ip, port=22, user='root', password='123456'):
    host_ip = host_ip
    user_name = user
    host_port = port

    # 注意:依次执行多条命令时,命令之间用分号隔开
    # command = sed_command + ";" + ls_command

    # SSH远程连接
    ssh = paramiko.SSHClient()  # 创建sshclient
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 指定当对方主机没有本机公钥的情况时应该怎么办,AutoAddPolicy表示自动在对方主机保存下本机的秘钥
    try:
        # 连接服务器
        ssh.connect(host_ip, port=host_port, username=user_name, password=password)
    except:
        print('连接%sip失败'%(host_ip))
    else:
        print('连接%s成功'%(host_ip))
        stdin, stdout, stderr = ssh.exec_command(cmd)
        out = stdout.read().decode('utf-8')
        err = stdout.read().decode('utf-8')
        if err:
            print('连接%s,操作失败' % (host_ip))
        else:
            print('连接%s,操作成功' % (host_ip))
    finally:
        ssh.close()
    return out, err


if __name__ == '__main__':
    # pwd = getpass.getpass("yss300377")
    result = ssh_connect('ls /root/', '127.0.0.1')

 

posted on 2019-11-06 15:28  蜗牛也是妞  阅读(568)  评论(0编辑  收藏  举报