python paramiko的使用

本文介绍了如何使用Python的Paramiko库进行远程命令执行、文件读取和文件存在性判断与创建。通过Paramiko,你可以轻松实现SSH连接到远程服务器进行自动化运维任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、远程执行命令

def remote_execution_command(ip,user,passwd,cmd,Ifsource,loginname=None,get_pty=False): 
    print_log('INFO','ip : %s,user : %s, cmd : %s  start\n' %(ip, user, cmd))
    #创建SSH对象
    ssh = paramiko.SSHClient()
    
    # 允许连接不在know_hosts文件中的主机
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    # 连接服务器
    try:
        ssh.connect(hostname=ip, port=22, username=user, password=passwd)
    except paramiko.ssh_exception.BadHostKeyException as e:
        msg = "the server's host key could not be verified. host: %s" % ip
        return (1, '', msg)
    except paramiko.ssh_exception.AuthenticationException as e:
        msg = 'authentication failed. host: %s' % ip
        return (1, '', msg)
    except Exception:
        msg = 'ssh connect failed. host: %s' % ip
        return (1, '', msg)

    #source .bash_profile环境变量,不然dbtool dbstate不能用
    if Ifsource == True:
        new_cmd = 'source /home/%s/.bash_profile; %s'%(user, cmd)
        #cmd = "bash -lc  '%s'"%(cmd)
    # 执行命令
    if loginname:
        new_cmd = 'su - %s -c "%s"' % (loginname, new_cmd)

    if get_pty == True:
        stdin, stdout, stderr = ssh.exec_command(new_cmd,get_pty=True)
        
    if get_pty == False:
        stdin, stdout, stderr = ssh.exec_command(new_cmd,get_pty=False)

    # 获取命令结果
    channel = stdout.channel
    status = channel.recv_exit_status()
 
    out_data = stdout.read()
    err_data = stderr.read()
    # 关闭连接
    ssh.close()
    return(status, out_data, err_data)

2、远程读取文件

def remote_read(ip,user,passwd,file_path):
    print_log("INFO", r'remote read ip : %s  file : %s'%(ip, file_path))
    client = paramiko.SSHClient()
    try:
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(ip, 22, user, passwd)
        sftp_client = client.open_sftp()
        remote_file = sftp_client.open(file_path, 'r+')
        str = remote_file.read()
        remote_file.close()
        return str
    except Exception as e:
        print_log('ERROR', 'failed to open the remote file : %s!'%e)
        sys.exit(1)
    finally:
        client.close()

3、远程判断文件是否存在以及创建文件

def remote_dir_state(ip,user,passwd,file_path):
    client = paramiko.SSHClient()
    try:
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(ip, 22, user, passwd)
        sftp_client = client.open_sftp()
        sftp_client.stat(file_path)
        print_log("INFO", "folder %s exist do not create it\n"%file_path)

    except IOError as e:
        print_log("INFO", "folder %s do not exist create it\n"%file_path)
        return 0
        
    except Exception as e:
        print_log('ERROR', 'failed to check file : %s,  %s exit'%(file_path, e))
        sys.exit(1)
        
    finally:
        client.close()
           
def remote_mkdir(ip,user,passwd,file_path):
    print_log("INFO", r'remote mkdir ip : %s  file : %s'%(ip, file_path))
    client = paramiko.SSHClient()
    try:
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(ip, 22, user, passwd)
        sftp_client = client.open_sftp()
        sftp_client.mkdir(file_path)
        print_log("INFO", "Create folder %s in remote hosts successfully!"%file_path)
    except Exception as e:
        print_log("ERROR", "Create folder %s in remote hosts failed! exit"%file_path)
        sys.exit(1)
    finally:
        client.close()

更多操作可以参考这里
paramiko

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值