python实现通过SSH访问linux并执行指令

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
import paramiko
from stat import S_ISDIR

class SSHSession:

    def __init__(self, ip, name, PWD):
        print 'SSH init...'
        self.client = paramiko.SSHClient()
        # 自动接受远程服务器host key
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.client.connect(ip, username=name, password=PWD)
        self.sftp = paramiko.SFTPClient.from_transport(self.client.get_transport())
        self.sftp = self.client.open_sftp()

    def getRemoteFile(self, remotefile, localfile):
        self.sftp.get(remotefile, localfile)

    def get_all_files_in_remote_dir(self, remote_dir):
        all_files = list()
        if remote_dir[-1] == '/':
            remote_dir = remote_dir[0:-1]
        remoteFiles = self.sftp.listdir_attr(remote_dir)
        for remoteFile in remoteFiles:
            filename = remote_dir + '/' + remoteFile.filename
            if S_ISDIR(remoteFile.st_mode):
                all_files.extend(self.get_all_files_in_remote_dir(filename))
            else:
                all_files.append(filename)

        print "all_files", all_files
        return all_files

    def get_all_files_in_local_dir(self, local_dir):
        all_files = list()
        print local_dir
        print local_dir[-2]
        if local_dir[-1:] == "\\":
            local_dir = local_dir[0:-1]
        # local_dir = local_dir[0:-1]
        localFiles = os.listdir(local_dir)
        print "1 localFiles:", localFiles
        for localFile in localFiles:
            # filename = local_dir + '//' + localFile.filename
            filename = os.path.join(local_dir, localFile)
            print filename
            if os.path.isdir(filename):
                #list param
                all_files.extend(self.get_all_files_in_local_dir(filename))
            else:
                #object
                all_files.append(filename)
        print "2 all_files:", all_files
        return all_files
    def copyRemoteFolder(self, remote_dir, local_dir):
        all_files = self.get_all_files_in_remote_dir(remote_dir)
        for fullfilename in all_files:
            remoteFilePath, filename = os.path.split(str(fullfilename))
            local_path = os.path.join(local_dir, remoteFilePath.split('/')[-1])
            if not os.path.exists(local_path):
                os.makedirs(local_path)
            local_filename = os.path.join(local_path, filename)
            print 'get files %s transporting...' % filename
            self.sftp.get(fullfilename, local_filename)

    def sendCommand(self, command):
        if self.client:
            channel = self.client.get_transport().open_session()
            channel.exec_command(command)
            return channel
        print 'Connection not opened.'

    def checkSSHconnection(self):
        if self.client:
            try:
                self.client.exec_command('ls', timeout=0.5)
                return True
            except Exception as e:
                print 'Connection lost : %s' % e
                return False

    def closeSSH(self):
        self.sftp.close()
        self.client.close()

    def __put_all_file(self, local_dir):
#         save all files list
        all_files = list()

        files = os.listdir(local_dir)
        for i in files:
#             
            filename = os.path.join(local_dir, i)
#             
            if os.path.isdir(i):
                all_files.extend(self.__put_all_file(filename))
            else:
                all_files.append(filename)

        return all_files

    def put_dir(self, local_dir, remote_dir):
        # 去掉字符串最后的字符
        if remote_dir[-1] == '/':
            remote_dir = remote_dir[0:-1]
        # 获取本地指定的目录及目录下的文件
        all_files = self.get_all_files_in_local_dir(local_dir)
        for i in all_files:
            filename = os.path.split(i)[-1]
            print local_dir,remote_dir
            remote_file = os.path.split(i)[0].replace(local_dir, remote_dir)
            path = remote_file.replace("\\", "/")
            print 'filename:' + filename
            print remote_file

            self.client.exec_command('mkdir -p ' + path)
            remote_filename = path + '/' + filename
            print u'Put files...' + filename
            self.sftp.put(i, remote_filename)


            # remote_filename = remote_dir + '/' + filename
            # print(u'Put文件{}传输中...'.format(filename))
            # self.sftp.put(i, remote_filename)


def main():
    SSH = SSHSession('192.168.56.101', 'root', 'suming')
    if SSH.checkSSHconnection():
        # SSH.copyRemoteFolder('/home/frank/log_test/', 'C:\\APP\\tool')
        SSH.put_dir('C:\\APP\\tool', '/home/frank/log_test/')
        # SSH.get_all_files_in_local_dir("C:\\APP\\tool\\")
    # for line in stdout:
    #     print(line)
    SSH.closeSSH()
if __name__ == '__main__':

    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值