本文整理匯總了Python中paramiko.SSHClient方法的典型用法代碼示例。如果您正苦於以下問題:Python paramiko.SSHClient方法的具體用法?Python paramiko.SSHClient怎麽用?Python paramiko.SSHClient使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類paramiko
的用法示例。
在下文中一共展示了paramiko.SSHClient方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: ssh_edit_file
# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHClient [as 別名]
def ssh_edit_file(adress, user, passw, remotefile, regex, replace):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
trans = paramiko.Transport((adress, 22))
trans.connect(username=user, password=passw)
sftp = paramiko.SFTPClient.from_transport(trans)
f_in = sftp.file(remotefile, "r")
c_in = f_in.read()
pattern = re.compile(regex, re.MULTILINE | re.DOTALL)
c_out = pattern.sub(replace, c_in)
f_out = sftp.file(remotefile, "w")
f_out.write(c_out)
f_in.close()
f_out.close()
sftp.close()
trans.close()
示例2: _ssh_run_remote_command
# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHClient [as 別名]
def _ssh_run_remote_command(self, cmd):
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=self.host,
username=self.config['ssh_user'],
password=self.config['ssh_password'])
stdin, stdout, stderr = ssh_client.exec_command(cmd)
out = stdout.read().decode().strip()
error = stderr.read().decode().strip()
if self.log_level:
logger.info(out)
if error:
raise Exception('There was an error pulling the runtime: {}'.format(error))
ssh_client.close()
return out
示例3: fetch_remote_crashes
# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHClient [as 別名]
def fetch_remote_crashes(self):
"""
some exception handling code is taken from https://www.programcreek.com/python/example/105570/scp.SCPClient
"""
try:
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect(hostname=config.remote_system_ip)
self.copy_crashes_dir_with_scp(ssh)
except AuthenticationException:
print("Authentication failed, please verify your credentials: %s")
except SSHException as sshException:
print("Unable to establish SSH connection: %s" % sshException)
except BadHostKeyException as badHostKeyException:
print("Unable to verify server's host key: %s" % badHostKeyException)
finally:
ssh.close()
示例4: __init__
# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHClient [as 別名]
def __init__(self, host, **ssh_kwargs):
"""
Parameters
----------
host: str
Hostname or IP as a string
temppath: str
Location on the server to put files, when within a transaction
ssh_kwargs: dict
Parameters passed on to connection. See details in
http://docs.paramiko.org/en/2.4/api/client.html#paramiko.client.SSHClient.connect
May include port, username, password...
"""
if self._cached:
return
super(SFTPFileSystem, self).__init__(**ssh_kwargs)
self.temppath = ssh_kwargs.pop("temppath", "/tmp")
self.host = host
self.ssh_kwargs = ssh_kwargs
self._connect()
示例5: pair
# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHClient [as 別名]
def pair(request):
server = SSHClientFixture()
thread = threading.Thread(target=server.run)
thread.daemon = True
thread.start()
client = S.SSHClient(server.addr, port=server.port,
username='slowdive',
password='pygmalion')
def fin():
server.tearDown()
client.close()
request.addfinalizer(fin)
return client, server
示例6: test_exec_command
# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHClient [as 別名]
def test_exec_command(client, mock):
def my_mock(*args):
return None, None, None
mock.patch.object(paramiko.SSHClient, 'connect')
mock.patch.object(paramiko.SSHClient, 'exec_command', my_mock)
stdin, stdout, stderr = client.exec_command('yes')
# def test_wait(pair):
# # TODO: fix unit test here
# client, server = pair
# client.con
# server.stdout('ok', delay=True)
# output = client.wait('yes')
# assert output == 'ok'
示例7: connect
# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHClient [as 別名]
def connect(self):
"""Call to set connection with remote client."""
try:
self.paramiko_session = paramiko.SSHClient()
self.paramiko_session.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
self.paramiko_session.connect(
self.client.ip, username=self.client.user,
password=self.client.pass_, key_filename=self.client.key,
allow_agent=True, compress=self.client.compress)
except (paramiko.AuthenticationException,
paramiko.ssh_exception.NoValidConnectionsError) as e:
self.logger.error(e)
sys.exit(colored("> {}".format(e), 'red'))
except paramiko.SSHException as e:
self.logger.error(e)
sys.exit(colored("> {}".format(e), 'red'))
self.transfer = network.Network(
self.paramiko_session, self.client.ip, self.client.port)
self.transfer.open()
示例8: _try_passwordless_paramiko
# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHClient [as 別名]
def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavailable, "
if sys.platform == 'win32':
msg += "Paramiko is required for ssh tunneled connections on Windows."
else:
msg += "use OpenSSH."
raise ImportError(msg)
username, server, port = _split_server(server)
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
client.connect(server, port, username=username, key_filename=keyfile,
look_for_keys=True)
except paramiko.AuthenticationException:
return False
else:
client.close()
return True
示例9: run
# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHClient [as 別名]
def run(self):
print("Start try ssh => %s" % self.ip)
username = "root"
try:
password = open(self.dict).read().split('\n')
except:
print("Open dict file `%s` error" % self.dict)
exit(1)
for pwd in password:
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self.ip, self.port, username, pwd, timeout = self.timeout)
print("\nIP => %s, Login %s => %s \n" % (self.ip, username, pwd))
open(self.LogFile, "a").write("[ %s ] IP => %s, port => %d, %s => %s \n" % (time.asctime( time.localtime(time.time()) ), self.ip, self.port, username, pwd))
break
except:
print("IP => %s, Error %s => %s" % (self.ip, username, pwd))
pass
示例10: _try_passwordless_paramiko
# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHClient [as 別名]
def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavaliable, "
if sys.platform == 'win32':
msg += "Paramiko is required for ssh tunneled connections on Windows."
else:
msg += "use OpenSSH."
raise ImportError(msg)
username, server, port = _split_server(server)
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
client.connect(server, port, username=username, key_filename=keyfile,
look_for_keys=True)
except paramiko.AuthenticationException:
return False
else:
client.close()
return True
示例11: main
# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHClient [as 別名]
def main():
'''
Use Paramiko to retrieve the entire 'show version' output.
'''
ip_addr = raw_input("Enter IP address: ")
username = 'pyclass'
password = getpass()
port = 22
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.load_system_host_keys()
remote_conn_pre.connect(ip_addr, port=port, username=username, password=password,
look_for_keys=False, allow_agent=False)
remote_conn = remote_conn_pre.invoke_shell()
time.sleep(1)
clear_buffer(remote_conn)
disable_paging(remote_conn)
output = send_command(remote_conn, cmd='show version')
print '\n>>>>'
print output
print '>>>>\n'
示例12: check_connections
# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHClient [as 別名]
def check_connections(function: Callable[..., Any]) -> Callable[..., Any]:
"""
A decorator designned for ``SSHClient``to check SSH connections before
calling a method. It first checks if ``self._ssh`` is available in a
SSHClient instance and then checks if you can send ``ls`` and get response
to make sure your connection still alive. If connection is bad, this
decorator will reconnect the SSH channel, to avoid connection related
error when executing the method.
"""
def decorator(*args, **kwargs) -> Any:
self = args[0]
if self._ssh is None: # not sure if some status may cause False
self._sftp, self._ssh = self.connect()
# test connection, reference:
# https://stackoverflow.com/questions/
# 20147902/how-to-know-if-a-paramiko-ssh-channel-is-disconnected
# According to author, maybe no better way
try:
self._ssh.exec_command('ls')
except Exception as e:
logger.debug(f'The connection is no longer valid. {e}')
self.connect()
return function(*args, **kwargs)
return decorator
示例13: sshInstall
# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHClient [as 別名]
def sshInstall(retry,hostname):
global user
global password
global userInsightfinder
global licenseKey
global samplingInterval
global reportingInterval
global agentType
if retry == 0:
print "Install Fail in", hostname
q.task_done()
return
print "Start installing agent in", hostname, "..."
try:
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if os.path.isfile(password) == True:
s.connect(hostname, username=user, key_filename = password, timeout=60)
else:
s.connect(hostname, username=user, password = password, timeout=60)
transport = s.get_transport()
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
session.exec_command("sudo rm -rf insightagent* InsightAgent* \n \
wget --no-check-certificate https://github.com/insightfinder/InsightAgent/archive/master.tar.gz -O insightagent.tar.gz && \
tar xzvf insightagent.tar.gz && \
cd InsightAgent-master && deployment/checkpackages.sh -env\n")
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
stdin.write(password+'\n')
stdin.flush()
session.recv_exit_status() #wait for exec_command to finish
s.close()
print "Install Succeed in", hostname
q.task_done()
return
except paramiko.SSHException, e:
print "Invalid Username/Password for %s:"%hostname , e
return sshInstall(retry-1,hostname)
示例14: sshStopCron
# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHClient [as 別名]
def sshStopCron(retry,hostname):
global user
global password
if retry == 0:
print "Stop Cron Failed in", hostname
q.task_done()
return
try:
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if os.path.isfile(password) == True:
s.connect(hostname, username=user, key_filename = password, timeout=60)
else:
s.connect(hostname, username=user, password = password, timeout=60)
transport = s.get_transport()
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
command = "sudo mv /etc/cron.d/ifagent InsightAgent-master/ifagent."+time.strftime("%Y%m%d%H%M%S")+"\n"
session.exec_command(command)
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
stdin.write(password+'\n')
stdin.flush()
session.recv_exit_status() #wait for exec_command to finish
s.close()
print "Stopped Cron in ", hostname
q.task_done()
return
except paramiko.SSHException, e:
print "Invalid Username/Password for %s:"%hostname , e
return sshStopCron(retry-1,hostname)
示例15: sshStopCron
# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHClient [as 別名]
def sshStopCron(retry,hostname):
global user
global password
if retry == 0:
print "Stop Cron Failed in", hostname
q.task_done()
return
try:
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if os.path.isfile(password) == True:
s.connect(hostname, username=user, key_filename = password, timeout=60)
else:
s.connect(hostname, username=user, password = password, timeout=60)
transport = s.get_transport()
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
command = "./InsightAgent-master/hypervisor/stopcron.sh -t hypervisor\n"
session.exec_command(command)
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
stdin.write(password+'\n')
stdin.flush()
session.recv_exit_status() #wait for exec_command to finish
s.close()
print "Stopped Cron in ", hostname
q.task_done()
return
except paramiko.SSHException, e:
print "Invalid Username/Password for %s:"%hostname , e
return sshStopCron(retry-1,hostname)