本文整理汇总了Python中paramiko.Transport类的典型用法代码示例。如果您正苦于以下问题:Python Transport类的具体用法?Python Transport怎么用?Python Transport使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Transport类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: write_redirects_to_sftp
def write_redirects_to_sftp(self, from_path, to_path, cron):
try:
ssh_key_object = RSAKey(filename=app.config['SFTP_SSH_KEY_PATH'],
password=app.config['SFTP_SSH_KEY_PASSPHRASE'])
remote_server_public_key = HostKeyEntry.from_line(app.config['SFTP_REMOTE_HOST_PUBLIC_KEY']).key
# This will throw a warning, but the (string, int) tuple will automatically be parsed into a Socket object
remote_server = Transport((app.config['SFTP_REMOTE_HOST'], 22))
remote_server.connect(hostkey=remote_server_public_key, username=app.config['SFTP_USERNAME'], pkey=ssh_key_object)
sftp = SFTPClient.from_transport(remote_server)
sftp.put(from_path, to_path)
if cron:
return 'SFTP publish from %s to %s succeeded' % (from_path, to_path)
else:
return fjson.dumps({
'type': 'success',
'message': 'Redirect updates successful'
})
except:
if cron:
return 'SFTP publish from %s to %s failed' % (from_path, to_path)
else:
return fjson.dumps({
'type': 'danger',
'message': 'Redirect updates failed'
})
示例2: __init__
class SshConnection:
""" tsc ssh connection """
def __init__(self, name, host, port=22, user=None, password=None):
""" init """
self.connection = None
self.session = None
self.host = host
self.port = port
self.loginAccount = {
'user': user,
'pass': password
}
self.name = name
self.timeout = 4
self.nbytes = 4096
try:
self.connection = Transport((self.host, self.port))
self.connection.connect(username=self.loginAccount['user'],
password=self.loginAccount['pass'])
self.connection.set_keepalive(self.timeout)
self.session = self.connection.open_channel(kind='session')
print('ssh connection created!')
except Exception, e:
self.__del__()
print('ssh connection failed: {er}'.format(er=e))
示例3: sftp_server
def sftp_server():
"""
Set up an in-memory SFTP server thread. Yields the client Transport/socket.
The resulting client Transport (along with all the server components) will
be the same object throughout the test session; the `sftp` fixture then
creates new higher level client objects wrapped around the client
Transport, as necessary.
"""
# Sockets & transports
socks = LoopSocket()
sockc = LoopSocket()
sockc.link(socks)
tc = Transport(sockc)
ts = Transport(socks)
# Auth
host_key = RSAKey.from_private_key_file(_support("test_rsa.key"))
ts.add_server_key(host_key)
# Server setup
event = threading.Event()
server = StubServer()
ts.set_subsystem_handler("sftp", SFTPServer, StubSFTPServer)
ts.start_server(event, server)
# Wait (so client has time to connect? Not sure. Old.)
event.wait(1.0)
# Make & yield connection.
tc.connect(username="slowdive", password="pygmalion")
yield tc
示例4: __init__
class SFTPCopy:
def __init__(self, host, port, username, password):
self.host = host
self.port = port
self.username = username
self.password = password
self.t = Transport((self.host, self.port))
self.t.connect(username=self.username, password=self.password) # 注意:此处需要用默认传参方式传参
self.sftp = SFTPClient.from_transport(self.t)
def copyData(self, localdir, remotedir):
for (root, dirs, files) in walk(localdir):
for dir in dirs:
dest = path.join(remotedir, root[len(localdir):][1:], dir)
try:
self.sftp.mkdir(dest)
except Exception as e:
print('ERROR: make directory %s %s' % (dest, e))
for file in files:
src = path.join(root, file)
dest = path.join(remotedir, root[len(localdir):][1:], file)
try:
self.sftp.put(src, dest)
except Exception as e:
print('ERROR: touch file %s %s' % (dest, e))
示例5: scp
def scp(self, srcFile, destPath):
transport = Transport((self.host, int(self.port)))
transport.connect(username=self.user, password=self.passwd)
sftp = SFTPClient.from_transport(transport)
try:
sftp.put(srcFile, destPath)
except IOError as e:
raise e
示例6: sftpOpenConnection
def sftpOpenConnection(self, target):
""" opens an sftp connection to the given target host;
credentials are taken from /etc/ssh/sftp_passwd """
from paramiko import Transport, SFTPClient
from paramiko.util import load_host_keys
hostname, username, password = self.getCredentials(target)
hostkeys = load_host_keys('/etc/ssh/ssh_known_hosts')
hostkeytype, hostkey = hostkeys[hostname].items()[0]
trans = Transport((hostname, 22))
trans.connect(username=username, password=password, hostkey=hostkey)
return SFTPClient.from_transport(trans)
示例7: run
def run(self):
self.socket.listen(100)
while True:
self.socket.settimeout(15)
s,addr = self.socket.accept()
transport = Transport(s)
transport.add_server_key(self.key)
event = Event()
#transport.set_subsystem_handler('', ShellHandler)
transport.start_server(event, server=self)
示例8: _createConnection
def _createConnection(self):
"""
@see: L{_createConnection<datafinder.persistence.common.connection.pool.ConnectionPool._createConnection>}
"""
try:
connection = Transport((self._configuration.hostname, DEFAULT_SSH_PORT))
connection.connect(username=self._configuration.username, password=self._configuration.password)
return connection
except (SSHException, socket.error, socket.gaierror), error:
errorMessage = u"Unable to establish SSH connection to TSM host '%s'! " \
% (self._configuration.hostname) + "\nReason: '%s'" % str(error)
raise PersistenceError(errorMessage)
示例9: sftpOpen
def sftpOpen(self, target):
""" opens an sftp connection to the given target host;
credentials are taken from /etc/ssh/sftp_passwd """
from paramiko import Transport, SFTPClient
#from paramiko.util import load_host_keys
print '>>> sftpOpen self.username: ', self.username
print ' self.password: ', self.password
print ' self.hostkey: ', self.password
print ' self.hostname: ', self.hostname
trans = Transport((self.hostname, 22))
trans.banner_timeout = 120
trans.connect(username=self.username,
password=self.password,
hostkey=self.hostkey)
return SFTPClient.from_transport(trans)
示例10: _authenticate
def _authenticate(self):
self._transport = SFTPTransport((self.config['sftp_host'],
self.config['sftp_port']))
self._transport.connect(username=self.config['sftp_user'],
password=self.config['sftp_password'])
self.session = SFTPClient.from_transport(self._transport)
logging.info('SFTP Authorization succeed')
示例11: __init__
def __init__(self, request, client_address, server):
self.request = request
self.client_address = client_address
self.tcp_server = server
# Keep track of channel information from the transport
self.channels = {}
try:
self.client = request._sock
except AttributeError as e:
self.client = request
# Transport turns the socket into an SSH transport
self.transport = Transport(self.client)
# Create the PTY handler class by mixing in
TelnetHandlerClass = self.telnet_handler
class MixedPtyHandler(TelnetToPtyHandler, TelnetHandlerClass):
# BaseRequestHandler does not inherit from object, must call the __init__ directly
def __init__(self, *args):
super(MixedPtyHandler, self).__init__(*args)
TelnetHandlerClass.__init__(self, *args)
self.pty_handler = MixedPtyHandler
# Call the base class to run the handler
BaseRequestHandler.__init__(self, request, client_address, server)
示例12: __init__
def __init__(self, host, port, user, pw):
self.transport = Transport((host, port))
self._datos = {'host': host, 'port': port, 'user': user, 'pw': pw}
self.rsa_key = None
self.setPrivateKey(expanduser('~/.ssh/id_rsa'))
self.conectar()
示例13: sshAuthentication
def sshAuthentication(self, clientsock):
# setup logging
paramiko.util.log_to_file(C.SYSLOG_FILE)
# Check that SSH server parameters have been set:
if (self.sshData == None):
return clientsock, False, None
else:
# Load private key of the server
filekey = self.sshData["hostKeyFile"]
if (not filekey.startswith("/")):
filekey = C.YENCAP_CONF_HOME + "/" + filekey
# Build a key object from the file path:
if (self.sshData["hostKeyType"] == "dss"):
priv_host_key = paramiko.DSSKey(filename=filekey)
elif (self.sshData["hostKeyType"] == "rsa"):
priv_host_key = paramiko.RSAKey(filename=filekey)
try:
event = threading.Event()
# Create a new SSH session over an existing socket, or socket-like object.
t = Transport(clientsock)
# Add a host key to the list of keys used for server mode.
t.add_server_key(priv_host_key)
# paramiko.ServerInterface defines an interface for controlling the behavior of paramiko in server mode.
server = SSHServerModule()
# Negotiate a new SSH2 session as a server.
t.start_server(event, server)
while 1:
event.wait(0.1)
if not t.is_active():
return clientsock, False, None
if event.isSet():
break
# Return the next channel opened by the client over this transport, in server mode.
channel = t.accept(20)
if channel is None:
return clientsock, False, None
except Exception, e:
LogManager.getInstance().logError("Caught exception: %s: %s" % (str(e.__class__), str(e)))
traceback.print_exc()
try:
t.close()
except:
pass
return clientsock, False, None
示例14: listdir
def listdir(hostname, path="/var/tmp", filter="", port=1035, username="", password=""):
"""
paramiko sftp listdir wrapper, with option to filter files
"""
# Paramiko client configuration
t = Transport((hostname, port))
t.connect(username=username, password=password)
sftp = SFTPClient.from_transport(t)
try:
rex = re.compile(filter)
except:
print "Invalid regular expression: " + filter
sys.exit(1)
return [x for x in sftp.listdir(path) if rex.match(x)]
示例15: connect
def connect(self, hostname_address):
"""connect to SSH target using paramiko Transport/Channel"""
self._transport = Transport(hostname_address)
self._transport.connect(username=self.user, password=self.passwd)
self.ssh_channel = self._transport.open_channel("session")
self.pty = self.ssh_channel.get_pty()
self.ssh_channel.invoke_shell()
self.wait_for_prompt()
self.ssh_channel.send("set cli screen-length 0")