Python 自动化paramiko操作linux使用shell命令,以及文件上传下载linux与windows之间的实现

摘要:
#![INFO]2019-05-1922:41:36Sun--root--sshutils.py˃˃runfunction::atline53:root66501016:33?00:00:56/usr/bin/python-Es/usr/sbin/firewalld--nofork--nopidroot72941016:33?00:00:11/usr/bin/python2-Es/usr/sbin/tuned-l-Proot6404164030022:41?
#!/usr/bin/python3
import paramiko
import os
import sys
import subprocess
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
from src.logutils import logger
log=logger("root",rootstdout=True,handlerList=['I','E'])
class SshConnect(object):

    def __init__(self,ip,user,pwd,port):
        self.port=port
        self.pwd=pwd
        self.user=user
        self.ip=ip
    def get_connected_client(self):
        client=paramiko.SSHClient()
        try:
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect(self.ip,self.port,self.user,self.pwd)
            if client:
                return client
        except ConnectionError as e:
            log.error(e)
    def exe_cmd(self,shell):
        client=self.get_connected_client()
        try:
            input, out, err =client.exec_command(shell)
            res,err = out.read(),err.read()
            result = res if res else err
            if type(result).__name__ == 'bytes':
                return result.decode('utf-8')
            elif type(result).__name__ == 'str':
                return result

        except Exception as e:
            log.error(e)
        finally:
            if client:
                client.close()
            else:
                log.info("ssh client is null not need close")

def run():
    ip='192.168.81.129'
    port=22
    pwd='admin'
    user='root'
    client=SshConnect(ip,user,pwd,port)
    res=client.exe_cmd('ps -ef|grep python&&df -m') #type should be str 
    log.info(res)

# def deal_res(res):
#     std=''
#     for i  in res:
#         output=i.decode("utf-8")
#         std +=output
#     return std

if __name__ == '__main__':
    run()
""" 
     注意点:remote_path 和 local_path , 
    路径必须为带文件名全路径只到目录路径会报:
     [Errno 13] Permission denied,若路径怕出错可以在最前面加r   """
        
def downlodfile_from_linux(self,remote_path,local_path):
    try:
        transport = paramiko.Transport(self.host ,self.port)
        transport.connect(username=self.user,password=self.pwd)
        sftp=paramiko.SFTPClient.from_transport(transport)
        sftp.get(remotepath=remote_path,localpath=local_path)
        transport.close()
    except Exception as e:
       log.error(e)
    else:
        log.info(" download ok")
def upload_file_to_linux(self,local_path,remote_path):
    try:
        transport = paramiko.Transport(self.host ,self.port)
        transport.connect(username=self.user,password=self.pwd)
        sftp=paramiko.SFTPClient.from_transport(transport)
        sftp.put(localpath=local_path,remotepath=remote_path)
        transport.close()
    except Exception as e:
        log.error(e)
    else:
        log.info("upload ok")

C:\Python37\python.exe C:/Users/Administrator/PycharmProjects/checkTest/src/sshutils.py
[INFO]2019-05-19 22:41:35 Sun --paramiko.transport-- transport.py>>_log function ::at line 1746 :
Connected (version 2.0, client OpenSSH_7.4)
[INFO]2019-05-19 22:41:35 Sun --paramiko.transport-- transport.py>>_log function ::at line 1746 :
Authentication (publickey) failed.
[INFO]2019-05-19 22:41:35 Sun --paramiko.transport-- transport.py>>_log function ::at line 1746 :
Authentication (password) successful!
[INFO]2019-05-19 22:41:36 Sun --root-- sshutils.py>>run function ::at line 53 :
root 6650 1 0 16:33 ? 00:00:56 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid
root 7294 1 0 16:33 ? 00:00:11 /usr/bin/python2 -Es /usr/sbin/tuned -l -P
root 64041 64030 0 22:41 ? 00:00:00 bash -c ps -ef|grep python&&df -m
root 64057 64041 0 22:41 ? 00:00:00 grep python
Filesystem 1M-blocks Used Available Use% Mounted on
/dev/mapper/centos-root 27627 8654 18974 32% /
devtmpfs 894 0 894 0% /dev
tmpfs 910 1 910 1% /dev/shm
tmpfs 910 11 900 2% /run
tmpfs 910 0 910 0% /sys/fs/cgroup
/dev/sda1 1014 232 783 23% /boot
tmpfs 182 1 182 1% /run/user/42
tmpfs 182 0 182 0% /run/user/0

免责声明:文章转载自《Python 自动化paramiko操作linux使用shell命令,以及文件上传下载linux与windows之间的实现》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇SQL Server dbcc checkdb 做了什么。链表的建立下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

python数据分析——pandas的拼接操作

pandas的拼接操作 pandas的拼接分为两种: 级联:pd.concat, pd.append 合并:pd.merge, pd.join 1. 使用pd.concat()级联 pandas使用pd.concat函数,与np.concatenate函数类似,只是多了一些参数: objs axis=0 keys join='outer' /...

Linux开机自启动的几种方式

Linux开机自启动的几种方式: 操作系统:linux mint 17.3 第一种方式:在/etc/rc.local文件中加入启动命令 这种方式适合linux用户手动配置自启动程序。 第二种方式:在/etc/rc[0-6].d/目录建立软链接,软链接指向/etc/init.d/目录下的控制脚本 下图可以看出/etc/rc2.d目录下的文件指向路径是/etc...

centos 7.2 网卡配置文件 及 linux bridge的静态配置

在 centos 7.2 系统内, 网卡的配置文件在: /etc/sysconfig/network-scripts/ 下。 命名规则: ifcfg-xxxx。 xxx为设备名称。 通过分析 network 服务的执行脚本:/etc/rc.d/init.d/network 整理网卡配置文件的内容: 1 TYPE=Ethernet              ...

配置SecureCRT连接VirtualBox虚拟机中的Linux环境

在实际的运维中我们常常使用SecuriteCRT来远程控制Linux服务器。下面将详细介绍windows 7下通过VirtualBox搭建linux开发环境,并最终通过SecurityCRT来远程访问linux服务器。 主要分为以下几个步骤 1、VirtualBox安装 2、Ubuntu安装 3、SecuriteCRT安装 4、配置Linux网络 一、我使...

【Python】使用socketserver建立一个异步TCP服务器

概述 这篇文章是讲解如何使用socketserver建立一个异步TCP服务器,其中Python版本为3.5.1。 socketserver主要的类 socketserver模块中的类主要有以下几个:1、BaseServer 包含服务器的核心功能与混合类(mix-in)的钩子功能。这个类主要用于派生,不要直接生成这个类的类对象,可以考虑使用TCPServer...

ASP漏洞+SQL注入的入侵方法

本文就是想对装上了防火墙的主机,进行入侵攻击的大概思路小结一下。 首先当然是用扫描器对这台服务器(以下简称主机A)进行常规的扫描,得到初步的信息。再用nmap -sS IP -P0 -p 139 ,透过防火墙查看是否开有139端口。从上面得到的信息我们可以简单的判断到:主机A的系统是什么,装有防火墙的 话,一般是只允许80端口开放的。如果能够泄漏asp源...