python3传文件到linux服务器然后解压

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import paramiko
import time
from scp import SCPClient



#将脚本传到服务器,并解压
def transRemote(ip,user,password):
    try:

        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, 22, username=user, password=password, timeout=200)
        stdin, stdout, stderr=ssh.exec_command("pwd")
        #path=stdout.read().strip("\n")

        # 获取路劲
        path= stdout.read().decode('utf-8').strip("\n")

        #查看python版本
        stdin, stdout, stderr=ssh.exec_command("python -V")
        print(stdout.read().decode('utf-8'))
        # pythonVsersion=stdout.read().strip("\n")
        pythonVsersion = stdout.read().decode('utf-8').strip("\n")
        scriptName="jixianjiancha.tar.gz"
        if(len(pythonVsersion)==0):
            scriptName="jixianjiancha.tar.gz"
        else:
            if(pythonVsersion.split()[1].startswith("3")):
                scriptName="jixianjiancha2.tar.gz"

        current_path=os.getcwd()
        #print current_path
        scpclient = SCPClient(ssh.get_transport(), socket_timeout=15.0)
        scpclient.put('%s\\check\\%s'%(current_path,scriptName), '%s/jixianjiancha.tar.gz'%path)
        print("[*]将脚本传送到远程服务器")

        index=0
        script_number=12
        while(index<10):
            stdin, stdout, stderr=ssh.exec_command('tar -xvf %s/jixianjiancha.tar.gz'%path)
            time.sleep(2)
            stdin, stdout, stderr=ssh.exec_command("ls %s"%(path))
            scripts=len(stdout.read().decode('utf-8').strip("\n"))
            if(scripts==12):
                index=11
            else:
                index+=1
        print("[*]在远程服务器上解压脚本")
        ssh.close()
        return True
    except Exception as e:
        print(e)
    return False

if __name__ == '__main__':
    transRemote('192.168.221.133','root','toor')

转载于:https://www.cnblogs.com/17bdw/p/11559514.html

你可能感兴趣的:(python3传文件到linux服务器然后解压)