import paramiko

from scp import SCPClient

class LinuxSSHSCP(object):

def __init__(self, ip, username, password, port=22):

self.ip = ip

self.username = username

self.password = password

self.port = port

self.ssh_client = None

self.scp_client = None

self.sftp_client = None

def ssh_connect(self):

print("ssh connect")

if self.ssh_client is None:

self.ssh_client = paramiko.SSHClient()

# set_missing_host_key_policy(paramiko.AutoAddPolicy()) 允许连接不在know_hosts文件中的主机

self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

self.ssh_client.connect(self.ip, self.port, self.username, self.password, timeout=10)

def ssh_disconnect(self):

print("ssh disconnect")

self.ssh_client.close()

self.ssh_client = None

def ssh_exec_command(self, command):

print("exec command on remote")

std_in, std_out, std_err = self.ssh_client.exec_command(command)

result = std_out.read().decode()

return result

def scp_connect(self):

print("scp connect")

if self.ssh_client is None:

print("ssh not connect, start connect ssh")

self.ssh_connect()

if self.scp_client is None:

self.scp_client = SCPClient(self.ssh_client.get_transport(), socket_timeout=15.0)

def scp_disconnect(self):

print("scp disconnect")

self.scp_client.close()

self.scp_client = None

def scp_copy_from_remote(self, local_path, remote_path):

print("start copy remote to local")

self.scp_client.get(remote_path, local_path, True)

def scp_copy_to_remote(self, local_path, remote_path):

print("start copy local to remote")

self.scp_client.put(local_path, remote_path, True)

def sftp_connect(self):

print("sftp connect")

if self.ssh_client is None:

self.ssh_connect()

self.sftp_client = self.ssh_client.open_sftp()

def sftp_copy_from_remote(self, local_path, remote_path):

print("sftp copy from remote")

self.sftp_client.get(remote_path, local_path)

def sftp_copy_to_remote(self, local_path, remote_path):

print("sftp copy to remote")

self.sftp_client.put(local_path, remote_path)

def sftp_disconnect(self):

print("sftp connect")

self.sftp_client.close()

self.sftp_client = None

if __name__ == "__main__":

# 使用scp远程拷贝 拷贝整个目录只要提供路径就可以

# s = LinuxSSHSCP("ip", "tester", "password", 22)

# s.ssh_connect()

# s.scp_connect()

# print(s.ssh_exec_command("ls /home/tester/ |grep test"))

# print(s.ssh_exec_command("touch /home/tester/scp_test.text"))

# s.scp_copy_from_remote("/home/test/demo/ssh_demo/", "/home/tester/scp_test.text")

# print(s.ssh_exec_command("ls /home/tester/ |grep test"))

# s.scp_copy_to_remote("/home/test/demo/ssh_demo/tester_password", "/home/tester/")

# print(s.ssh_exec_command("ls /home/tester/ |grep test"))

# s.scp_disconnect()

# s.ssh_disconnect()

# 使用sftp远程拷贝 拷贝整个目录需要先获取目录下所有的文件名字,然后依次拷贝

s = LinuxSSHSCP("ip", "tester", "password", 22)

s.ssh_connect()

s.sftp_connect()

print(s.ssh_exec_command("ls /home/tester/ |grep test"))

print(s.ssh_exec_command("touch /home/tester/scp_test.txt"))

s.sftp_copy_from_remote("/home/test/demo/ssh_demo/scp_test.txt", "/home/tester/scp_test.txt")

print(s.ssh_exec_command("ls /home/tester/ |grep test"))

s.sftp_copy_to_remote("/home/test/demo/ssh_demo/tester_password", "/home/tester/tester_password")

print(s.ssh_exec_command("ls /home/tester/ |grep test"))

s.sftp_disconnect()

s.ssh_disconnect()

files = open('/tmp/deploy.log','a')

try:

files.write('[%s]: %s \n' %(time.ctime(),info))

except IOError:

files.close()

files.close()

def cmds(self,host,comm):

try:

print comm

client = paramiko.Transport((host,int(self.port)))

client.connect(username=self.users,password=self.passwd)

chan = client.open_session()

chan.exec_command(comm)

chan.close()

except:

print 'host', host

print traceback.format_exc()

self.log(traceback.format_exc())

def sftps(self,host,files):

try:

lodir = '/opt/onfile'

rmdir = '/opt/onfile'

client = paramiko.Transport((host,int(self.port)))

client.connect(username=self.users,password=self.passwd)

sftp = paramiko.SFTPClient.from_transport(client)

sftp.put('%s/%s'%(lodir,files),'%s/%s'%(rmdir,files))

client.close()

except:

print traceback.format_exc()

self.log(traceback.format_exc())

def work(self,comm):

fp = open('/opt/online/ser_list.txt').readlines()

for s in fp:

host = s.strip()

self.cmds(host,comm)

def sftp(self,comm):

fp = open('/opt/online/ser_list.txt').readlines()

for s in fp:

host = s.strip()

self.sftps(host,files)

if __name__ == '__main__':

外汇返佣

sc = Remote()

func =  sys.argv[1]

files = sys.argv[2]

if func == 'sftp':

sc.sftp(files)

elif func == 'work':

sc.work(files)

Python远程执行命令和拷贝

使用paramiko库和scp库结合

import paramiko

from scp import SCPClient

class LinuxSSHSCP(object):

def __init__(self, ip, username, password, port=22):

self.ip = ip

self.username = username

self.password = password

self.port = port

self.ssh_client = None

self.scp_client = None

self.sftp_client = None

def ssh_connect(self):

print("ssh connect")

if self.ssh_client is None:

self.ssh_client = paramiko.SSHClient()

# set_missing_host_key_policy(paramiko.AutoAddPolicy()) 允许连接不在know_hosts文件中的主机

self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

self.ssh_client.connect(self.ip, self.port, self.username, self.password, timeout=10)

def ssh_disconnect(self):

print("ssh disconnect")

self.ssh_client.close()

self.ssh_client = None

def ssh_exec_command(self, command):

print("exec command on remote")

std_in, std_out, std_err = self.ssh_client.exec_command(command)

result = std_out.read().decode()

return result

def scp_connect(self):

print("scp connect")

if self.ssh_client is None:

print("ssh not connect, start connect ssh")

self.ssh_connect()

if self.scp_client is None:

self.scp_client = SCPClient(self.ssh_client.get_transport(), socket_timeout=15.0)

def scp_disconnect(self):

print("scp disconnect")

self.scp_client.close()

self.scp_client = None

def scp_copy_from_remote(self, local_path, remote_path):

print("start copy remote to local")

self.scp_client.get(remote_path, local_path, True)

def scp_copy_to_remote(self, local_path, remote_path):

print("start copy local to remote")

self.scp_client.put(local_path, remote_path, True)

def sftp_connect(self):

print("sftp connect")

if self.ssh_client is None:

self.ssh_connect()

self.sftp_client = self.ssh_client.open_sftp()

def sftp_copy_from_remote(self, local_path, remote_path):

print("sftp copy from remote")

self.sftp_client.get(remote_path, local_path)

def sftp_copy_to_remote(self, local_path, remote_path):

print("sftp copy to remote")

self.sftp_client.put(local_path, remote_path)

def sftp_disconnect(self):

print("sftp connect")

self.sftp_client.close()

self.sftp_client = None

if __name__ == "__main__":

# 使用scp远程拷贝 拷贝整个目录只要提供路径就可以

# s = LinuxSSHSCP("ip", "tester", "password", 22)

# s.ssh_connect()

# s.scp_connect()

# print(s.ssh_exec_command("ls /home/tester/ |grep test"))

# print(s.ssh_exec_command("touch /home/tester/scp_test.text"))

# s.scp_copy_from_remote("/home/test/demo/ssh_demo/", "/home/tester/scp_test.text")

# print(s.ssh_exec_command("ls /home/tester/ |grep test"))

# s.scp_copy_to_remote("/home/test/demo/ssh_demo/tester_password", "/home/tester/")

# print(s.ssh_exec_command("ls /home/tester/ |grep test"))

# s.scp_disconnect()

# s.ssh_disconnect()

# 使用sftp远程拷贝 拷贝整个目录需要先获取目录下所有的文件名字,然后依次拷贝

s = LinuxSSHSCP("ip", "tester", "password", 22)

s.ssh_connect()

s.sftp_connect()

print(s.ssh_exec_command("ls /home/tester/ |grep test"))

print(s.ssh_exec_command("touch /home/tester/scp_test.txt"))

s.sftp_copy_from_remote("/home/test/demo/ssh_demo/scp_test.txt", "/home/tester/scp_test.txt")

print(s.ssh_exec_command("ls /home/tester/ |grep test"))

s.sftp_copy_to_remote("/home/test/demo/ssh_demo/tester_password", "/home/tester/tester_password")

print(s.ssh_exec_command("ls /home/tester/ |grep test"))

s.sftp_disconnect()

s.ssh_disconnect()

#!/usr/bin/env python

#-*-coding:UTF-8-*-

"""

@Item   :  v1.0

@Author :  ShengWangQiang

@Group  :  System

@Date   :  2015-01-28

@E-mail :  swq.499809608@hotmail.com

@Funtion:

"""

import sys,time,os,traceback,commands,

import paramiko,

class Remote(object):

def __init__(self):

version = 'v0.1'

self.users = 'root'

self.passwd  = "1234567890"

self.port = 22

def log(self,info):

files = open('/tmp/deploy.log','a')

try:

files.write('[%s]: %s \n' %(time.ctime(),info))

except IOError:

files.close()

files.close()

def cmds(self,host,comm):

try:

print comm

client = paramiko.Transport((host,int(self.port)))

client.connect(username=self.users,password=self.passwd)

chan = client.open_session()

chan.exec_command(comm)

chan.close()

except:

print 'host', host

print traceback.format_exc()

self.log(traceback.format_exc())

def sftps(self,host,files):

try:

lodir = '/opt/onfile'

rmdir = '/opt/onfile'

client = paramiko.Transport((host,int(self.port)))

client.connect(username=self.users,password=self.passwd)

sftp = paramiko.SFTPClient.from_transport(client)

sftp.put('%s/%s'%(lodir,files),'%s/%s'%(rmdir,files))

client.close()

except:

print traceback.format_exc()

self.log(traceback.format_exc())

def work(self,comm):

fp = open('/opt/online/ser_list.txt').readlines()

for s in fp:

host = s.strip()

self.cmds(host,comm)

def sftp(self,comm):

fp = open('/opt/online/ser_list.txt').readlines()

for s in fp:

host = s.strip()

self.sftps(host,files)

if __name__ == '__main__':

sc = Remote()

func =  sys.argv[1]

files = sys.argv[2]

if func == 'sftp':

sc.sftp(files)

elif func == 'work':

sc.work(files)

Python执行和拷贝的更多相关文章

  1. 采用Psyco实现python执行速度提高到与编译语言一样的水平

    本文实例讲述了采用Psyco实现python执行速度提高到与编译语言一样的水平的方法,分享给大家供大家参考.具体实现方法如下: 一.安装Psyco很简单,它有两种安装方式,一种是源码方式,一种是二进制 ...

  2. Python执行系统命令的方法 os.system(),os.popen(),commands

    os.popen():用python执行shell的命令,并且返回了结果,括号中是写shell命令 Python执行系统命令的方法: https://my.oschina.net/renwofei42 ...

  3. python执行linux的shell命令

    python执行shell脚本常用的方法 import os val=os.system("shell语句")  >>> val=os.system(" ...

  4. python执行mysqldump命令

    本文简单讲述如何利用python执行一些sql语句,例如执行mysqldump命令,进行数据库备份,备份成sql文件 #!/usr/bin/python#导入os模块import os#导入时间模块i ...

  5. python执行shell获取硬件参数写入mysql

    最近要获取服务器各种参数,包括cpu.内存.磁盘.型号等信息.试用了Hyperic HQ.Nagios和Snmp,它们功能都挺强大的,但是于需求不是太符,亦或者太heavy. 于是乎想到用python ...

  6. Python原理 -- 深浅拷贝

    python原理 -- 深浅拷贝 从数据类型说开去 str, num : 一次性创建, 不能被修改, 修改即是再创建. list,tuple,dict,set : 链表,当前元素记录, 下一个元素的位 ...

  7. python执行方式及变量

    .python执行方式 (1)交互式:调试方便,无法保存代码 (2)命令行方式:可以永久保存代码 (3)python执行阶段 先启动python解释器,解释器像文本编辑器一样将文件内容从硬盘读到内存, ...

  8. python中深浅拷贝

    python的复制,深拷贝和浅拷贝的区别   在python中,对象赋值实际上是对象的引用.当创建一个对象,然后把它赋给另一个变量的时候,python并没有拷贝这个对象,而只是拷贝了这个对象的引用 一 ...

  9. Mysql学习---使用Python执行存储过程

    使用Python执行存储过程 使用Python执行存储过程[2部分]: 1.执行存储过程,获取存储过程的结果集  2.将返回值设置给了  @_存储过程名_序号 = #!/usr/bin/env pyt ...

随机推荐

  1. idea 离线安装 lombok插件

    Lombok简介 Lombok是Java语言的实用工具,确切的说,应该说是一个很好用的插件,对,插件!可以用来帮助开发人员消除Java代码的冗长,尤其是对于简单的Java对象(POJO),它通过注解实 ...

  2. 【leetcode】572. Subtree of Another Tree

    题目如下: Given two non-empty binary trees s and t, check whether tree t has exactly the same structure ...

  3. v-for中的key的使用【key的作用主要是是为了高效的更新虚拟DOM】

    vue中列表循环需加:key="唯一标识" 唯一标识可以是item里面id index等,因为vue组件高度复用增加Key可以标识组件的唯一性,为了更好地区别各个组件 key的作用 ...

  4. java生成快递单并调用打印机打印

    生成快递单过程中需要生成条形码,生成条形码可参考:https://www.cnblogs.com/linbky/p/12091248.html 下面这段代码生成的快递单是完全符合京东快递的10 x 1 ...

  5. Codechef BINOMSUM

    题意:(复制sunset的)有\(T\)天,每天有\(K\)个小时,第\(i\)天有\(D+i−1\)道菜,第一个小时你选择\(L\)道菜吃,接下来每个小时你可以选择吃一道菜或者选择\(A\)个活动中 ...

  6. Delphi界面篇之ListView控件

    //增加项或列(字段) ListView1.Clear; ListView1.Columns.Clear; ListView1.Columns.Add; ListView1.Columns.Add; ...

  7. RHEL 使用epel源

    转自http://www.linuxidc.com/Linux/2012-10/71850.htm 设置epel源.方法如下: 32位系统选择:rpm -ivh http://download.Fed ...

  8. 全国5A级旅游景区已达250家

    至目前,全国5A级旅游景区已达250家,快来数数你去过多少? 全国5A级旅游景区 西藏(+) 拉萨市大昭寺.拉萨布达拉宫景区.日喀则扎什伦布寺景区.林芝巴松措景区 新增1:日喀则扎什伦布寺景区 扎什伦 ...

  9. Python学习笔记二--函数

    1.使用global语句定义全局变量 2.默认参数 默认参数值应该是不可变的.注意: 只有在形参表末尾的那些参数可以有默认参数值,即你不能在声明函数形参的时候,先声明有默认值的形参而后声明没有默认值的 ...

  10. VMWARE ESXI 虚拟硬盘的格式:精简置备、厚置备延迟置零、厚置备置零

    精简置备(thin): 精 简配置就是无论磁盘分配多大,实际占用存储大小是现在使用的大小,即用多少算多少.当客户机有输入输出的时候,VMkernel首先分配需要的空间并进行 清零操作,也就是说如果使用 ...