def sftp_upload(host,port,username,password,local,remote):
sf = paramiko.Transport((host,port))
sf.connect(username = username,password = password)
sftp = paramiko.SFTPClient.from_transport(sf)
try:
if os.path.isdir(local):#?????????????
for f in os.listdir(local):#??????
sftp.put(os.path.join(local+f),os.path.join(remote+f))#????????
else:
sftp.put(local,remote)#????
except Exception,e:
print('upload exception:',e)
sf.close()
#if __name__ == '__main__':
# host = '121.69.75.194'#??
# port = 22 #??
# username = 'wac' #???
# password = '8112whz' #??
# local = '/Users/ngxin/Documents/xin/face_recognition/my_faces/'
# remote = '/home/wac/ngxin/ftp_upload/'
# local = 'F:\\sftptest\\'#?????????????????windows?????window???????????
# remote = '/opt/tianpy5/python/test/'#?????????????????linux????
#sftp_upload(host,port,username,password,local,remote)#??
#sftp_download(host,port,username,password,local,remote)#??
python类Transport()的实例源码
6_2_copy_remote_file_over_sftp.py 文件源码
项目:Python-Network-Programming-Cookbook-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def copy_file(hostname, port, username, password, src, dst):
client = paramiko.SSHClient()
client.load_system_host_keys()
print (" Connecting to %s \n with username=%s... \n" %(hostname,username))
t = paramiko.Transport(hostname, port)
t.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
print ("Copying file: %s to path: %s" %(src, dst))
sftp.put(src, dst)
sftp.close()
t.close()
def get_remote_file(hostname, port, username, password, remotepath, localpath):
"""Get remote file to local machine.
Args:
hostname(str): Remote IP-address
port(int): Remote SSH port
username(str): Remote host username for authentication
password(str): Remote host password for authentication
remotepath(str): Remote file to download location path
localpath(str): Local path to save remote file
Examples::
get_remote_file(host, port, username, password, tar_remotepath, tar_localpath)
"""
transport = paramiko.Transport((hostname, port))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
try:
sftp.get(remotepath=remotepath, localpath=localpath)
finally:
sftp.close()
transport.close()
def sftp(self,model=None,queue=None):
self.sshConn = paramiko.Transport((self.hostname,self.port))
self.sshConn.connect(username=self.username, password=self.password)
sftp = SSH(ssh=self.sshConn,hostname=self.hostname,
queue=queue,model=model)
return sftp
def handle_tcp_ssh(socket, dstport):
try:
t = paramiko.Transport(socket)
t.local_version = 'SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2'
t.load_server_moduli() # It can be safely commented out if it does not work on your system
t.add_server_key(host_key_rsa)
t.add_server_key(host_key_dss)
server = Server(socket.getpeername())
t.start_server(server=server)
t.join()
except Exception as err:
#print(traceback.format_exc())
pass
try:
print("-- SSH TRANSPORT CLOSED --")
t.close()
except:
pass
socket.close()
def handle(self):
transport = paramiko.Transport(self.request)
transport.add_server_key(pysshrp.common.config.keyData)
transport.set_subsystem_handler('sftp', paramiko.SFTPServer, SFTPInterface)
transport.start_server(server=self.clientthread)
while transport.is_active() and pysshrp.common.running:
time.sleep(1)
def __repr__(self):
"""
Returns a string representation of this object, for debugging.
"""
out = '<paramiko.Transport at %s' % hex(long(id(self)) & xffffffff)
if not self.active:
out += ' (unconnected)'
else:
if self.local_cipher != '':
out += ' (cipher %s, %d bits)' % (self.local_cipher,
self._cipher_info[self.local_cipher]['key-size'] * 8)
if self.is_authenticated():
out += ' (active; %d open channel(s))' % len(self._channels)
elif self.initial_kex_done:
out += ' (connected; awaiting auth)'
else:
out += ' (connecting)'
out += '>'
return out
def get_cam_config(target_ip, target_user, target_pass, cam_config_loc_on_pi):
config_name = cam_config_loc_on_pi.split("/")[-1]
localpath = tempfolder + config_name
try:
port = 22
ssh_tran = paramiko.Transport((target_ip, port))
print(" - connecting transport pipe... " + target_ip + " port:" + str(port))
ssh_tran.connect(username=target_user, password=target_pass)
sftp = paramiko.SFTPClient.from_transport(ssh_tran)
print("looking for " + str(cam_config_loc_on_pi))
sftp.get(cam_config_loc_on_pi, localpath)
print("--config file collected from pi--")
sftp.close()
ssh_tran.close()
except Exception as e:
print("!!! There was an issue, " + str(e))
return None
return localpath
def get_test_pic(target_ip, target_user, target_pass, image_to_collect):
img_name = image_to_collect.split("/")[-1]
localpath = tempfolder + img_name
try:
port = 22
ssh_tran = paramiko.Transport((target_ip, port))
print(" - connecting transport pipe... " + target_ip + " port:" + str(port))
ssh_tran.connect(username=target_user, password=target_pass)
sftp = paramiko.SFTPClient.from_transport(ssh_tran)
sftp.get(image_to_collect, localpath)
print("--image collected from pi--")
sftp.close()
ssh_tran.close()
except Exception as e:
print("!!! There was an issue, " + str(e))
return None
return localpath
def get_test_pic_from_list(target_ip, target_user, target_pass, image_list):
out_list = []
try:
port = 22
ssh_tran = paramiko.Transport((target_ip, port))
print(" - connecting transport pipe... " + target_ip + " port:" + str(port))
ssh_tran.connect(username=target_user, password=target_pass)
sftp = paramiko.SFTPClient.from_transport(ssh_tran)
except Exception as e:
print("!!! There was an issue, " + str(e))
return None
for image_to_collect in image_list:
print image_to_collect
img_name = image_to_collect.split("/")[-1]
localpath = tempfolder + img_name
print localpath
sftp.get(image_to_collect, localpath)
print("--image " + str(image_to_collect) + " collected from pi--")
out_list.append(localpath)
sftp.close()
ssh_tran.close()
return out_list
def get_sftp(hostname, port=22, user='root', keyfile=None, password=None,
keypw=None, pkey=None):
"""Get an SFTP connection using paramiko and plumbum.
"""
def get_transport(**kwargs):
transport = paramiko.Transport(hostname, port)
transport.connect(**kwargs)
return transport
def get_sftp(transport):
return paramiko.SFTPClient.from_transport(transport)
if keyfile:
pkey = pkey or get_pkey(keyfile, password=keypw)
try:
transport = get_transport(username=user, pkey=pkey)
return get_sftp(transport)
except paramiko.ssh_exception.AuthenticationException:
log.warn("Failed to auth ssh with keyfile {}".format(keyfile))
log_message = "Trying SSH connection to {} with credentials {}:{}"
log.info(log_message.format(hostname, user, password))
transport = get_transport(username=user, password=password)
return get_sftp(transport)
def sockthread(self):
while True:
try:
conn, addr = self.listensock.accept()
if not conn:
return
except:
return
self.transport = paramiko.Transport(conn)
self.transport.add_server_key(self.server_key)
if self.enable_sftp:
self.transport.set_subsystem_handler('sftp', SFTPHandler)
self.transport.start_server(server=self)
t2 = threading.Thread(target=self.transportthread)
t2.setDaemon(True)
t2.start()
def __init__(self, sock, addr):
super(SshServer, self).__init__()
# tweak InternalApi and RootCmd for non-bgp related commands
self.api = InternalApi(log_handler=logging.StreamHandler(sys.stderr))
setattr(self.api, 'sshserver', self)
self.root = RootCmd(self.api)
self.root.subcommands['help'] = self.HelpCmd
self.root.subcommands['quit'] = self.QuitCmd
transport = paramiko.Transport(sock)
transport.load_server_moduli()
host_key = self._find_ssh_server_key()
transport.add_server_key(host_key)
self.transport = transport
transport.start_server(server=self)
def __repr__(self):
"""
Returns a string representation of this object, for debugging.
"""
out = '<paramiko.Transport at %s' % hex(long(id(self)) & xffffffff)
if not self.active:
out += ' (unconnected)'
else:
if self.local_cipher != '':
out += ' (cipher %s, %d bits)' % (self.local_cipher,
self._cipher_info[self.local_cipher]['key-size'] * 8)
if self.is_authenticated():
out += ' (active; %d open channel(s))' % len(self._channels)
elif self.initial_kex_done:
out += ' (connected; awaiting auth)'
else:
out += ' (connecting)'
out += '>'
return out
def init_loopback():
global sftp, tc
socks = LoopSocket()
sockc = LoopSocket()
sockc.link(socks)
tc = paramiko.Transport(sockc)
ts = paramiko.Transport(socks)
host_key = paramiko.RSAKey.from_private_key_file(test_path('test_rsa.key'))
ts.add_server_key(host_key)
event = threading.Event()
server = StubServer()
ts.set_subsystem_handler('sftp', paramiko.SFTPServer, StubSFTPServer)
ts.start_server(event, server)
tc.connect(username='slowdive', password='pygmalion')
event.wait(1.0)
sftp = paramiko.SFTP.from_transport(tc)
def __repr__(self):
"""
Returns a string representation of this object, for debugging.
"""
out = '<paramiko.Transport at %s' % hex(long(id(self)) & xffffffff)
if not self.active:
out += ' (unconnected)'
else:
if self.local_cipher != '':
out += ' (cipher %s, %d bits)' % (self.local_cipher,
self._cipher_info[self.local_cipher]['key-size'] * 8)
if self.is_authenticated():
out += ' (active; %d open channel(s))' % len(self._channels)
elif self.initial_kex_done:
out += ' (connected; awaiting auth)'
else:
out += ' (connecting)'
out += '>'
return out
def __repr__(self):
"""
Returns a string representation of this object, for debugging.
"""
out = '<paramiko.Transport at %s' % hex(long(id(self)) & xffffffff)
if not self.active:
out += ' (unconnected)'
else:
if self.local_cipher != '':
out += ' (cipher %s, %d bits)' % (
self.local_cipher,
self._cipher_info[self.local_cipher]['key-size'] * 8
)
if self.is_authenticated():
out += ' (active; %d open channel(s))' % len(self._channels)
elif self.initial_kex_done:
out += ' (connected; awaiting auth)'
else:
out += ' (connecting)'
out += '>'
return out
def getpeername(self):
"""
Return the address of the remote side of this Transport, if possible.
This is effectively a wrapper around ``getpeername`` on the underlying
socket. If the socket-like object has no ``getpeername`` method, then
``("unknown", 0)`` is returned.
:return:
the address of the remote host, if known, as a ``(str, int)``
tuple.
"""
gp = getattr(self.sock, 'getpeername', None)
if gp is None:
return 'unknown', 0
return gp()
def transferdb():
global curp
#cmd = "mkdir /work/db"
#execcmd(cmd)
plan = assignplan()
for ip in plan:
ssh = paramiko.Transport((ip, 22))
#ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(ssh)
print "################################ %s ################################## " % ip
for f in plan[ip]:
print "\nPut ", f
curp = 0
fname = f.split('/')[-1]
sftp.put(f,'/work/db/'+fname, callback=showprocess)
sftp.close()
def __repr__(self):
"""
Returns a string representation of this object, for debugging.
"""
out = '<paramiko.Transport at %s' % hex(long(id(self)) & xffffffff)
if not self.active:
out += ' (unconnected)'
else:
if self.local_cipher != '':
out += ' (cipher %s, %d bits)' % (
self.local_cipher,
self._cipher_info[self.local_cipher]['key-size'] * 8
)
if self.is_authenticated():
out += ' (active; %d open channel(s))' % len(self._channels)
elif self.initial_kex_done:
out += ' (connected; awaiting auth)'
else:
out += ' (connecting)'
out += '>'
return out
def getpeername(self):
"""
Return the address of the remote side of this Transport, if possible.
This is effectively a wrapper around ``getpeername`` on the underlying
socket. If the socket-like object has no ``getpeername`` method, then
``("unknown", 0)`` is returned.
:return:
the address of the remote host, if known, as a ``(str, int)``
tuple.
"""
gp = getattr(self.sock, 'getpeername', None)
if gp is None:
return 'unknown', 0
return gp()
def close(self):
"""Closes the connection and cleans up."""
# Close SFTP Connection.
if self._sftp_live:
self._sftp.close()
self._sftp_live = False
# Close the SSH Transport.
if self._transport:
self._transport.close()
self._transport = None
# clean up any loggers
if self._cnopts.log:
# if handlers are active they hang around until the app exits
# this closes and removes the handlers if in use at close
import logging
lgr = logging.getLogger("paramiko")
if lgr:
lgr.handlers = []
def _connect_paramiko(self):
remote = (self.host, self.port or 22)
logging.debug('connect_paramiko: host=%s port=%s', *remote)
self.transport = paramiko.Transport(remote)
self.transport.connect()
logging.debug('connect_paramiko: connected')
try:
self._check_host_key(self.host)
except BaseException:
self.transport.close()
self.transport = None
raise
logging.debug('connect_paramiko: host key checked')
self._authenticate(self.user)
logging.debug('connect_paramiko: authenticated')
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
logging.debug('connect_paramiko: end')
def __repr__(self):
"""
Returns a string representation of this object, for debugging.
"""
out = '<paramiko.Transport at %s' % hex(long(id(self)) & xffffffff)
if not self.active:
out += ' (unconnected)'
else:
if self.local_cipher != '':
out += ' (cipher %s, %d bits)' % (self.local_cipher,
self._cipher_info[self.local_cipher]['key-size'] * 8)
if self.is_authenticated():
out += ' (active; %d open channel(s))' % len(self._channels)
elif self.initial_kex_done:
out += ' (connected; awaiting auth)'
else:
out += ' (connecting)'
out += '>'
return out
07_03_print_remote_cpu_info.py 文件源码
项目:011_python_network_programming_cookbook_demo
作者: jerry-0824
项目源码
文件源码
阅读 17
收藏 0
点赞 0
评论 0
def print_remote_cpu_info(hostname, port, username, password):
client = paramiko.Transport((hostname, port))
client.connect(username = username, password = password)
stdout_data = []
stderr_data = []
session = client.open_channel(kind='session')
session.exec_command(COMMAND)
while True:
if session.recv_ready():
stdout_data.append(session.recv(RECV_BYTES))
if session.recv_stderr_ready():
stderr_data.append(session.recv_stderr(RECV_BYTES))
if session.exit_status_ready():
break
print 'exit status: ', session.recv_exit_status()
print ''.join(stdout_data)
print ''.join(stderr_data)
session.close()
client.close()
def __repr__(self):
"""
Returns a string representation of this object, for debugging.
"""
out = '<paramiko.Transport at %s' % hex(long(id(self)) & xffffffff)
if not self.active:
out += ' (unconnected)'
else:
if self.local_cipher != '':
out += ' (cipher %s, %d bits)' % (self.local_cipher,
self._cipher_info[self.local_cipher]['key-size'] * 8)
if self.is_authenticated():
out += ' (active; %d open channel(s))' % len(self._channels)
elif self.initial_kex_done:
out += ' (connected; awaiting auth)'
else:
out += ' (connecting)'
out += '>'
return out
def sftp_conn(self):
""""""
try:
self.transport = paramiko.Transport((self.host, self.port))
self.transport.connect(username = self.username, password = self.password)
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
return True
except paramiko.AuthenticationException:
G.log(G.ERROR, "SFTP Authentication failed when connecting to %s" % self.host)
return False
except:
G.log(G.ERROR, "SFTP Could not SSH to %s, waiting for it to start" % self.host)
return False
#----------------------------------------------------------------------
def handle(self, *args, **kwargs):
t = paramiko.Transport(self.request)
t.add_server_key(host_key)
# Note that this actually spawns a new thread to handle the requests.
# (Actually, paramiko.Transport is a subclass of Thread)
t.start_server(server=self.server)
# wait for auth
chan = t.accept(20)
time_taken = 0.0
while getattr(chan, 'spoonybard_command', False) is False:
time.sleep(0.25)
time_taken += 0.25
if time_taken > command_timeout:
break
if chan is None:
print('No channel')
t.close()
return
if getattr(chan, 'spoonybard_command', False):
cmd = chan.spoonybard_command.split(' ')[0]
args = ' '.join(chan.spoonybard_command.split(' ')[1:])
command = spoonybard.engine.plugins.get_command_handler(cmd)
if command is None:
chan.send('Sorry, %s is an unknown command.\n' % cmd)
else:
if command.parse_args(args):
command.execute(chan)
else:
command.help(chan)
chan.close()
t.close()
def _connect(self):
self._transport = paramiko.Transport((self.url.host, self.url.port or self._DEFAULT_PORT))
self._transport.connect(self._get_hostkey(),
self.url.user,
self.url.password,
gss_host=socket.getfqdn(self.url.host),
gss_auth=self.GSS_AUTH,
gss_kex=self.GSS_KEX)
self.__client = paramiko.SFTPClient.from_transport(self._transport)
self.__client.chdir()
def _get_sftp_client(username, apikey):
"""Construct a paramiko SFTP client connected to drop.jarvice.com
using the user's Nimbix credentials.
Args:
username(str): Nimbix username for platform.jarvice.com
apikey(str): Nimbix apikey for platform.jarvice.com
"""
transport = paramiko.Transport(('drop.jarvice.com', 22))
transport.connect(username=username, password=apikey)
sftp = paramiko.SFTPClient.from_transport(transport)
return sftp