def _connect(self): transport = paramiko.Transport((self._host, self._port)) transport.connect(username=self._username, password=self._password) self._transport = transport
# coding=utf-8 # 上传文件到远程 import paramiko t = paramiko.Transport(("192.168.1.211", 22)) t.connect(username="******", password="******") sftp = paramiko.SFTPClient.from_transport(t) remotepath = '/tmp/test.txt' localpath = 'D:/test.txt' sftp.put(localpath, remotepath) t.close()
def initialize(self): try: # try importing here so we can catch it right away import paramiko except ImportError: util.Error('Paramiko libraries required for this module.') return level = getattr(paramiko.common, 'CRITICAL') paramiko.common.logging.basicConfig(level=level) # if the user did not specify a key, generate one if self.priv_key is None: if not util.check_program('openssl'): util.Error('OpenSSL required to generate cert/key files.') return if not util.does_file_exist('./privkey.key'): util.debug('Generating RSA private key...') tmp = util.init_app('openssl genrsa -out privkey.key 2048', True) util.debug('privkey.key was generated.') self.priv_key = './privkey.key' try: server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) server_socket.settimeout(3) server_socket.bind(('0.0.0.0', 22)) server_socket.listen(1) self.running = True while self.running: try: con, addr = server_socket.accept() except KeyboardInterrupt: return except: # timeout continue pkey = paramiko.RSAKey.from_private_key_file(self.priv_key) transport = paramiko.Transport(con) transport.add_server_key(pkey) transport.set_subsystem_handler('handler', paramiko.SFTPServer, SSHHandler) context = { 'dump': self.dump, 'log_data': self.log_data, 'log_file': self.log_file } server = SSHStub(context) try: transport.start_server(server=server) channel = transport.accept() while transport.is_active(): sleep(1) except socket.error as j: if j.errno == 104: # just means we've got a broken pipe, or # the peer dropped unexpectedly continue else: raise Exception() except IOError: util.Error('There was an error reading the keyfile.') return False except EOFError: # thrown when we dont get the key correctly, or # remote host gets mad because the key changed continue except: raise Exception() except KeyboardInterrupt: pass except Exception as j: util.Error('Error with server: %s' % j) finally: self.running = False self.cleanup()
nbytes = 4096 hostname = [ "fa18-cs425-g63-01.cs.illinois.edu", "fa18-cs425-g63-02.cs.illinois.edu", "fa18-cs425-g63-03.cs.illinois.edu", "fa18-cs425-g63-04.cs.illinois.edu", "fa18-cs425-g63-05.cs.illinois.edu", "fa18-cs425-g63-06.cs.illinois.edu", "fa18-cs425-g63-07.cs.illinois.edu", "fa18-cs425-g63-08.cs.illinois.edu", "fa18-cs425-g63-09.cs.illinois.edu", "fa18-cs425-g63-10.cs.illinois.edu" ] port = 22 username = getpass.getpass('Username: '******'Password: '******'cd mp4-ys26-weilinz2/ && ./clean.sh' for i in range(len(hostname)): client = paramiko.Transport((hostname[i], port)) client.connect(username=username, password=password) stdout_data = [] stderr_data = [] session = client.open_channel(kind='session') session.exec_command(command) # write and flush? while True: if session.recv_ready(): stdout_data.append(session.recv(nbytes)) if session.recv_stderr_ready(): stderr_data.append(session.recv_stderr(nbytes)) if session.exit_status_ready(): break
port = 22 if hostname.find(":") >= 0: hostname, portstr = hostname.split(":") port = int(portstr) # now connect try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hostname, port)) except Exception as e: print("*** Connect failed: " + str(e)) traceback.print_exc() sys.exit(1) try: t = paramiko.Transport(sock) try: t.start_client() except paramiko.SSHException: print("*** SSH negotiation failed.") sys.exit(1) try: keys = paramiko.util.load_host_keys( os.path.expanduser("~/.ssh/known_hosts") ) except IOError: try: keys = paramiko.util.load_host_keys( os.path.expanduser("~/ssh/known_hosts") )
def non_root_test_cb_vault_hvault(self): try: passed = False command1 = 'kubectl -n dev-core get pods | awk \'{print $1}\'' command2 = 'kubectl -n dev-core exec -it pod -- ps -eaf | sed \'1d;$d\'| awk \'{print $2}\'' client1 = paramiko.Transport((hostname, port)) client1.connect(username=username, password=password) session1 = client1.open_channel(kind='session') session1.exec_command(command1) while True: if session1.recv_ready(): stdout_data1.append(session1.recv(nbytes)) if session1.recv_stderr_ready(): stderr_data1.append(session1.recv_stderr(nbytes)) if session1.exit_status_ready(): break print 'exit status: ', session1.recv_exit_status() resp1 = ''.join(stdout_data1) print resp1 session1.close() client1.close() line = resp1.split('\n') p = [e for e in line if e.startswith('cb-vault-hvault')] print p[0] stdout_data = [] stderr_data = [] client = paramiko.Transport((hostname, port)) client.connect(username=username, password=password) session = client.open_channel(kind='session') print p[0] command2 = command2.replace("pod", p[0]) print command2 session.exec_command(command2) command2 = command2.replace(p[0], "pod") while True: if session.recv_ready(): stdout_data.append(session.recv(nbytes)) if session.recv_stderr_ready(): stderr_data.append(session.recv_stderr(nbytes)) if session.exit_status_ready(): break print 'exit status: ', session.recv_exit_status() resp2 = ''.join(stdout_data) print resp2 x = resp2.rsplit() print x[0] if x[0] == 'root': passed = False else: passed = True session.close() client.close() status['CAM-APITest'] = passed return passed except: status['CAM-APITest'] = False return False
def loginSession(): client = paramiko.Transport((hostname, port)) client.connect(username=username, password=password) session = client.open_channel(kind='session') return session
else: db_export(db_conn, exp['sql'], csvwriter, arraysize, debug) outf.close() # ZIP # zip_prefix = config['site']['site_abbrev'] + '_' + config['site'][ 'cdm_name'].lower() + '_' + datetime.date.today().strftime("%Y%m%d") zip_fname = zip_prefix + ".zip" if create_zip == True: print('Zipping ' + zip_fname) shutil.make_archive(zip_prefix, 'zip', output_dir) # SFTP # if sftp_zip == True: print("sftp zip file {}\n".format(zip_fname)) #python -m pip install paramiko import paramiko paramiko.util.log_to_file("sftp.log") # get key sftpkey = paramiko.RSAKey.from_private_key_file(config['sftp']['keyfile']) # open paramiko transport hp = config['sftp']['host'] + ':' + config['sftp']['port'] transport = paramiko.Transport(hp) # authenticate transport.connect(username=config['sftp']['user'], pkey=sftpkey) # sftp client sftp = paramiko.SFTPClient.from_transport(transport) sftp.chdir(config['sftp']['remote_dir']) sftp.put(zip_fname, zip_fname)
__author__ = "Alex Li" import paramiko transport = paramiko.Transport(('192.168.0.233', 22)) transport.connect(username='******', password='******') sftp = paramiko.SFTPClient.from_transport(transport) # 将location.py 上传至服务器 /tmp/test.py #sftp.put('笔记', '/tmp/test_from_win') # 将remove_path 下载到本地 local_path sftp.get('/root/oldgirl.txt', 'fromlinux.txt') transport.close()
def start_server(): """Init and run the ssh server""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', PORT)) except Exception as err: print('*** Bind failed: {}'.format(err)) traceback.print_exc() sys.exit(1) while True: try: sock.listen(100) print('Listening for connection ...') client, addr = sock.accept() except Exception as err: print('*** Listen/accept failed: {}'.format(err)) traceback.print_exc() LOG.write("\n\nConnection from: " + addr[0] + "\n") print('Got a connection!') try: transport = paramiko.Transport(client) transport.add_server_key(HOST_KEY) # Change banner to appear legit on nmap (or other network) scans transport.local_version = "SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.3" server = session() try: transport.start_server(server=server) except paramiko.SSHException: print('*** SSH negotiation failed.') raise Exception("SSH negotiation failed") # wait for auth chan = transport.accept(20) if chan is None: print('*** No channel.') raise Exception("No channel") server.event.wait(10) if not server.event.is_set(): print('*** Client never asked for a shell.') raise Exception("No shell request") try: chan.send("Welcome to the my control server\r\n\r\n") run = True while run: chan.send("$root@kali ") command = "" while not command.endswith("\r"): transport = chan.recv(1024) # Echo input to psuedo-simulate a basic terminal chan.send(transport) command += transport.decode("utf-8") chan.send("\r\n") command = command.rstrip() LOG.write("$ " + addr[0] + ' ' + command + "\n") print(command) if command == "exit": run = False else: handle_cmd(command, chan) except Exception as err: print('!!! Exception: {}: {}'.format(err.__class__, err)) traceback.print_exc() try: transport.close() except Exception: pass chan.close() except Exception as err: print('!!! Exception: {}: {}'.format(err.__class__, err)) traceback.print_exc() try: transport.close() except Exception: pass
def get_ssh_connection(self, hostname, username="******", password=None, keypath=None, proxy=None, proxy_username=None, proxy_password=None, proxy_keypath=None, key_files=None, enable_ipv6_dns=None, port=22, timeout=60, retry=1, verbose=False): """ Create a paramiko ssh session to hostname. Will attempt to authenticate first with a keypath if provided, if the sshkey file path is not provided. username and password will be used to authenticate. This leaves out the case where a password is passed as the password needed to unlock the key file. This 3rd case may need to be added but may mask failures in tests for key insertion when using tests who's images have baked in passwords for login access(tbd). Upon success returns a paramiko sshclient with an established connection. :param hostname: - mandatory - hostname or ip to establish ssh connection with :param username: - optional - username used to authenticate ssh session :param password: - optional - password used to authenticate ssh session :param keypath: - optional - full path to sshkey file used to authenticate ssh session :param proxy: - optional - host to proxy ssh connection through :param proxy_username: - optional ssh username of proxy host for authentication :param proxy_password: - optional ssh password of proxy host for authentication :param proxy_keypath: - optional path to ssh key to use for proxy authentication :param timeout: - optional - tcp timeout :param enable_ipv6_dns: - optional - boolean to avoid ipv6 dns 'AAAA' lookups :param retry: - optional - Number of attempts to establish ssh connection for errors outside of authentication :param port: - optional - port to connect to, default 22 :param verbose: - optional - enable verbose debug output """ connected = False iplist = [] ip = None key_files = key_files or self.key_files or [] if key_files and not isinstance(key_files, types.ListType): key_files = key_files.split(',') proxy_ip = None if not key_files and password is None and keypath is None and not self.find_keys: raise Exception( "ssh_connect: Need to set password, keypath, keyfiles, or find_keys" ) if enable_ipv6_dns is None: enable_ipv6_dns = self.enable_ipv6_dns proxy = proxy or self.proxy self.debug("ssh_connect args:\nhostname:" + hostname + "\nusername:"******"\npassword:"******"\nkeypath:" + str(keypath) + "\nproxy_username:"******"\nproxy_password" + str(proxy_password) + "\nproxy_keypath" + str(proxy_keypath) + "\ntimeout:" + str(timeout) + "\nretry:" + str(retry), verbose=verbose) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) hostname = str(hostname.strip()) if not enable_ipv6_dns: self.debug( 'IPV6 DNS lookup disabled, do IPV4 resolution and pass IP to connect()', verbose=verbose) # Paramiko uses family type 'AF_UNSPEC' which does both ipv4/ipv6 lookups and can cause some DNS servers # to fail in their response(s). Hack to avoid ipv6 lookups... # Try ipv4 dns resolution of 'hostname', and pass the ip instead of a hostname to # Paramiko's connect to avoid the potential ipv6 'AAAA' lookup... iplist = self.get_ipv4_lookup(hostname, verbose=verbose) if not iplist: iplist = [hostname] attempt = 0 #adjust retry count for debug 'readability' ie 'attempt 1' vs 'attempt 0' retry += 1 while (attempt < retry) and not connected: attempt += 1 proxy_transport = None for ip in iplist: if self.proxy: if not enable_ipv6_dns: proxy_ip = self.get_ipv4_lookup(self.proxy, verbose=verbose)[0] proxy_transport = self.get_proxy_transport( proxy_host=proxy, dest_host=ip, port=port, proxy_username=proxy_username, proxy_password=proxy_password, proxy_keypath=proxy_keypath) if proxy_transport: ssh._transport = proxy_transport else: ssh._transport = paramiko.Transport(ip) ssh._transport.start_client() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: self.debug("SSH connection attempt(" + str(attempt) + " of " + str(retry) + "), host:'" + username + "@" + hostname + "', using ipv4:" + str(ip) + ", thru proxy:'" + str(proxy_ip) + "'") if keypath is None and password: self.debug("Using username:"******" and password:"******"Using Keypath:" + keypath, verbose=verbose) priv_key = paramiko.RSAKey.from_private_key_file( keypath) ssh._transport.auth_publickey(username, priv_key) #ssh.connect(ip, port=port, username=username, key_filename=keypath, timeout=timeout) connected = True break elif key_files or self.find_keys: self.debug( "Using local keys, no keypath/password provided.", verbose=verbose) ssh._auth(username, password, None, key_files, True, True) #ssh.connect(ip, port=port, username=username, key_filename=keypath, timeout=timeout) connected = True except paramiko.ssh_exception.SSHException, se: self.debug("Failed to connect to " + hostname + ", retry in 10 seconds. Err:" + str(se)) time.sleep(10) pass if connected: via_string = '' if proxy_transport: proxy_host, port = ssh._transport.getpeername() via_string = ' via proxy host:' + str( proxy_host) + ':' + str(port) self.debug('SSH - Connected to ' + str(ip) + str(via_string)) break
def ssh_client_handler(sock, address, out_trans, logfile, kill_switch, hijack_flag): # If we're sniffing ssh, we also need to create # an SSH server that's listening for inbound conns in_trans = paramiko.Transport(sock) in_trans.load_server_moduli() in_trans.add_server_key(host_key) ssh_sniff = sshniffer(endpoint=out_trans, logfile=logfile) resp_expected = False enable = False try: in_trans.start_server(server=ssh_sniff) if args.debug: print_good("[0.0] Sucessfully negotiated SSH with inbound target") except: print_bad("[x.x] Couldnt negotiate ssh with inbound target") sys.exit(1) #client authenticates to us, we pass along to endpoint, and respond accordingly if args.debug: print "[<.<] Accepting transport..." in_chan = in_trans.accept(60) if retry_hack: out_trans = ssh_sniff.get_endpoint() if args.debug: print "[?.?] Transport accepted?" if not in_chan: print_bad("[x.x] Failed Auth, killing connection") in_trans.close() out_trans.close() sys.exit(1) if args.debug: print_good("[o.o] Negotiated shell session with inbound target") conn_hijack = False if args.hijack: conn_hijack = True #create our channel (exec/shell/subsystem...) out_chan = create_ssh_channel(out_trans) #needed since the pty causes only 1 char at a time to be sent >_> log_buffer = "" echo_expected = False hijack_buff = "" # hijack buff for detecting "exit\r" if filtering: ssh_sniff.netkit.init_client_buffer(in_chan, out_chan) while True and not kill_switch.is_set(): # since we're not using select() time.sleep(.01) tmp = "" #take bytes from impersonated ssh, send to user if out_chan.recv_ready(): inb = get_bytes(out_chan) if len(inb): # save response for output print_warn(inb) #print "Prefilter inb: %s" % repr(inb) if filtering: inb = ssh_sniff.netkit.inbound_filter(inb) if len(inb): #print "Post filter inb: %s" % repr(inb) in_chan.send(inb) resp_expected = False #don't want to log char-by-char reponses if len(inb) > 3: logfile.write("<<<<<<<<<<<<<\n") logfile.write(inb + '\n') inb = "" #test if endpoint is closed or not try: out_chan.send("") except Exception as e: print_purp(str(e)) break #take bytes from user, send to impersonated if in_chan.recv_ready(): outb = get_bytes(in_chan) if len(outb): log_buffer += outb if filtering: outb = ssh_sniff.netkit.outbound_filter(outb) if not len(outb): continue if outb[-1] == "\r": logfile.write(">>>>>>>>>>>>>\n") logfile.write(repr(log_buffer) + '\n') log_buffer = "" print_attn(repr(outb)) try: out_chan.send(outb) if filtering: # Due to SSH, when we send anything, # we should get echo back of what we sent. # Discard immediately. discard = "" while len(discard) < len(outb): discard += get_bytes(out_chan) newline_ind = discard.find("\r") print_attn("ignoring: %s\n" % discard[:newline_ind]) discard = discard[newline_ind:] # since we're discarding newline in_chan.send(discard) except Exception as e: print_purp(str(e)) break resp_expected = True inb = "" try: if ssh_sniff.netkit.client_buffer.hijack_flag == True: print "Setting Hijack" hijack_flag.set() except Exception as e: print e pass ###### ##/end while True and not kill_switch.is_set(): ###### # close for the client in_trans.close() prev_inb = "" if not conn_hijack or not hijack_flag.is_set(): out_trans.close() print_warn("[;.;] Client connection closed %s:%d" % (address[0], address[1])) print_good("[-.-]zzzZZZZZzzzzzZZ") else: hijack_flag.clear() # Begin hijack listener try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((IP, HIJINX_PORT)) print_attn("[>,0] Bound to local SSH interface %s%s:%d" % (WARN, IP, HIJINX_PORT)) except: print_bad("[x.x] Unable to bind to %s:%d" % (IP, HIJINX_PORT)) return sock.listen(1) keep_alive_flag = threading.Event() out_chan_keepalive = threading.Thread(target=chan_keepalive, args=(keep_alive_flag, out_chan)) out_chan_keepalive.start() while True: print_good("[-.-]Hijinx: zzzZZZZ") try: client, addr = sock.accept() print_attn("[!.!] connection from %s:%d" % (addr[0], addr[1])) except KeyboardInterrupt: print_attn("[^.^] Killing the hijinx") return in_trans = paramiko.Transport(client) in_trans.load_server_moduli() in_trans.add_server_key(host_key) ssh_sniff = hijacked_sshniffer(logfile=logfile) try: in_trans.start_server(server=ssh_sniff) if args.debug: print_good( "[0.0] Sucessfully negotiated SSH with hijacker") except: print_bad("[x.x] Couldnt negotiate ssh with inbound target") return in_chan = in_trans.accept(30) if not in_chan: print_bad("[x.x] Failed Auth, killing connection") continue else: break # end keepalive keep_alive_flag.set() in_chan.send("[^.^] Welcome to the Hijinx server [^.^]\r") logfile.write("HIJAX" * 5) while True and not kill_switch.is_set(): # since we're not using select() time.sleep(.01) tmp = "" #take bytes from impersonated ssh, send to user if out_chan.recv_ready(): inb = get_bytes(out_chan) if len(inb): # save response for output print_warn(inb) #print "INB: %s" % repr(inb) in_chan.send(inb) resp_expected = False #don't want to log char-by-char reponses if len(inb) > 3: logfile.write("<<<<<<<<<<<<<\n") logfile.write(inb + '\n') inb = "" #If there's no output from impersonated, just break if resp_expected: try: #if we get bytes, false alarm inb = get_bytes(out_chan) print_warn(inb) #print "INB: %s" % repr(inb) in_chan.send(inb) inb = "" resp_expected = False logfile.write(inb + '\n') except Exception as e: print str(e) #no bytes => conn closed break if in_chan.recv_ready(): outb = get_bytes(in_chan) if len(outb): log_buffer += outb if outb == "\r": logfile.write(">>>>>>>>>>>>>\n") logfile.write(repr(log_buffer) + '\n') log_buffer = "" print_attn(repr(outb)) try: out_chan.send(outb) except Exception as e: print_purp(str(e)) break resp_expected = True inb = "" # close for the client in_trans.close() hijack_flag.set()
def download(self, local_path, remote_path): self.ssh = paramiko.Transport((self.host, self.port)) self.ssh.connect(username=self.username, password=self.password) sftp = paramiko.SFTPClient.from_transport(self.ssh) sftp.get(remote_path, local_path)
ssh_port = int(sys.argv[2]) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((server, ssh_port)) sock.listen(100) print '[+] Listen on connection ...' client, addr = sock.accept() except Exception, e: print '[-] Listen failed :' + str(e) sys.exit(1) print '[+] Get a connection' try: bhsession = paramiko.Transport(client) bhsession.set_gss_host(socket.getfqdn("")) try: bhsession.load_server_moduli except: print "Failed to load moduli" raise bhsession.add_server_key(host_key) server = Server() try: bhsession.start_server(server=server) except paramiko.ssh_exception, x: print '[-] SSH negotiation failed.' chan = bhsession.accept(20) print '[+] Authenticated'
def ssh_channel(self, bind_host_user_obj, models): hostname = bind_host_user_obj.host.ip_addr # ip addr port = bind_host_user_obj.host.port username = bind_host_user_obj.host_user.username password = bind_host_user_obj.host_user.password # now connect try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hostname, port)) except Exception as e: print('*** Connect failed: ' + str(e)) traceback.print_exc() sys.exit(1) try: t = paramiko.Transport(sock) try: t.start_client() except paramiko.SSHException: print('*** SSH negotiation failed.') sys.exit(1) try: keys = paramiko.util.load_host_keys( os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: keys = paramiko.util.load_host_keys( os.path.expanduser('~/ssh/known_hosts')) except IOError: print('*** Unable to open host keys file') keys = {} # check server's host key -- this is important. key = t.get_remote_server_key() if hostname not in keys: print('*** WARNING: Unknown host key!') elif key.get_name() not in keys[hostname]: print('*** WARNING: Unknown host key!') elif keys[hostname][key.get_name()] != key: print('*** WARNING: Host key has changed!!!') sys.exit(1) else: print('*** Host key OK.') # agent_auth(t, username) if not t.is_authenticated(): manual_auth(t, username, hostname, password) if not t.is_authenticated(): print('*** Authentication failed. :(') t.close() sys.exit(1) chan = t.open_session() chan.get_pty() chan.invoke_shell() print('*** Here we go!\n') # 创建session对象 session_obj = models.SessionLog.objects.create( account=self.user, bind_host_user=bind_host_user_obj) # 将session_obj 传入 interactive.interactive_shell(chan, models, session_obj) chan.close() t.close() except Exception as e: print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e)) traceback.print_exc() try: t.close() except: pass sys.exit(1)
def connect(self): self._transport = paramiko.Transport((self.host, self.port)) self._transport.connect(username=self.username, password=self.pwd) self.ssh = paramiko.SSHClient() self.ssh._transport = self._transport
def connect(self, host, port=830, timeout=None, unknown_host_cb=default_unknown_host_cb, username=None, password=None, key_filename=None, allow_agent=True, hostkey_verify=True, look_for_keys=True, ssh_config=None): """Connect via SSH and initialize the NETCONF session. First attempts the publickey authentication method and then password authentication. To disable attempting publickey authentication altogether, call with *allow_agent* and *look_for_keys* as `False`. *host* is the hostname or IP address to connect to *port* is by default 830, but some devices use the default SSH port of 22 so this may need to be specified *timeout* is an optional timeout for socket connect *unknown_host_cb* is called when the server host key is not recognized. It takes two arguments, the hostname and the fingerprint (see the signature of :func:`default_unknown_host_cb`) *username* is the username to use for SSH authentication *password* is the password used if using password authentication, or the passphrase to use for unlocking keys that require it *key_filename* is a filename where a the private key to be used can be found *allow_agent* enables querying SSH agent (if found) for keys *hostkey_verify* enables hostkey verification from ~/.ssh/known_hosts *look_for_keys* enables looking in the usual locations for ssh keys (e.g. :file:`~/.ssh/id_*`) *ssh_config* enables parsing of an OpenSSH configuration file, if set to its path, e.g. :file:`~/.ssh/config` or to True (in this case, use :file:`~/.ssh/config`). """ # Optionaly, parse .ssh/config config = {} if ssh_config is True: ssh_config = "~/.ssh/config" if sys.platform != "win32" else "~/ssh/config" if ssh_config is not None: config = paramiko.SSHConfig() config.parse(open(os.path.expanduser(ssh_config))) config = config.lookup(host) host = config.get("hostname", host) if username is None: username = config.get("user") if key_filename is None: key_filename = config.get("identityfile") if username is None: username = getpass.getuser() sock = None if config.get("proxycommand"): sock = paramiko.proxy.ProxyCommand(config.get("proxycommand")) else: for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: sock = socket.socket(af, socktype, proto) sock.settimeout(timeout) except socket.error: continue try: sock.connect(sa) except socket.error: sock.close() continue break else: raise SSHError("Could not open socket to %s:%s" % (host, port)) t = self._transport = paramiko.Transport(sock) t.set_log_channel(logger.name) if config.get("compression") == 'yes': t.use_compression() try: t.start_client() except paramiko.SSHException: raise SSHError('Negotiation failed') # host key verification server_key = t.get_remote_server_key() fingerprint = _colonify(hexlify(server_key.get_fingerprint())) if hostkey_verify: known_host = self._host_keys.check(host, server_key) if not known_host and not unknown_host_cb(host, fingerprint): raise SSHUnknownHostError(host, fingerprint) if key_filename is None: key_filenames = [] elif isinstance(key_filename, (str, bytes)): key_filenames = [ key_filename ] else: key_filenames = key_filename self._auth(username, password, key_filenames, allow_agent, look_for_keys) self._connected = True # there was no error authenticating # TODO: leopoul: Review, test, and if needed rewrite this part subsystem_names = self._device_handler.get_ssh_subsystem_names() for subname in subsystem_names: c = self._channel = self._transport.open_session() self._channel_id = c.get_id() channel_name = "%s-subsystem-%s" % (subname, str(self._channel_id)) c.set_name(channel_name) try: c.invoke_subsystem(subname) except paramiko.SSHException as e: logger.info("%s (subsystem request rejected)", e) handle_exception = self._device_handler.handle_connection_exceptions(self) # Ignore the exception, since we continue to try the different # subsystem names until we find one that can connect. #have to handle exception for each vendor here if not handle_exception: continue self._channel_name = c.get_name() self._post_connect() return raise SSHError("Could not open connection, possibly due to unacceptable" " SSH subsystem name.")
def connect( self, host, port = PORT_NETCONF_DEFAULT, timeout = None, unknown_host_cb = default_unknown_host_cb, username = None, password = None, key_filename = None, allow_agent = True, hostkey_verify = True, hostkey_b64 = None, look_for_keys = True, ssh_config = None, sock_fd = None, bind_addr = None): """Connect via SSH and initialize the NETCONF session. First attempts the publickey authentication method and then password authentication. To disable attempting publickey authentication altogether, call with *allow_agent* and *look_for_keys* as `False`. *host* is the hostname or IP address to connect to *port* is by default 830 (PORT_NETCONF_DEFAULT), but some devices use the default SSH port of 22 so this may need to be specified *timeout* is an optional timeout for socket connect *unknown_host_cb* is called when the server host key is not recognized. It takes two arguments, the hostname and the fingerprint (see the signature of :func:`default_unknown_host_cb`) *username* is the username to use for SSH authentication *password* is the password used if using password authentication, or the passphrase to use for unlocking keys that require it *key_filename* is a filename where a the private key to be used can be found *allow_agent* enables querying SSH agent (if found) for keys *hostkey_verify* enables hostkey verification from ~/.ssh/known_hosts *hostkey_b64* only connect when server presents a public hostkey matching this (obtain from server /etc/ssh/ssh_host_*pub or ssh-keyscan) *look_for_keys* enables looking in the usual locations for ssh keys (e.g. :file:`~/.ssh/id_*`) *ssh_config* enables parsing of an OpenSSH configuration file, if set to its path, e.g. :file:`~/.ssh/config` or to True (in this case, use :file:`~/.ssh/config`). *sock_fd* is an already open socket which shall be used for this connection. Useful for NETCONF outbound ssh. Use host=None together with a valid sock_fd number *bind_addr* is a (local) source IP address to use, must be reachable from the remote device. """ if not (host or sock_fd): raise SSHError("Missing host or socket fd") self._host = host # Optionally, parse .ssh/config config = {} if ssh_config is True: ssh_config = "~/.ssh/config" if sys.platform != "win32" else "~/ssh/config" if ssh_config is not None: config = paramiko.SSHConfig() with open(os.path.expanduser(ssh_config)) as ssh_config_file_obj: config.parse(ssh_config_file_obj) # Save default Paramiko SSH port so it can be reverted paramiko_default_ssh_port = paramiko.config.SSH_PORT # Change the default SSH port to the port specified by the user so expand_variables # replaces %p with the passed in port rather than 22 (the defauld paramiko.config.SSH_PORT) paramiko.config.SSH_PORT = port config = config.lookup(host) # paramiko.config.SSHconfig::expand_variables is called by lookup so we can set the SSH port # back to the default paramiko.config.SSH_PORT = paramiko_default_ssh_port host = config.get("hostname", host) if username is None: username = config.get("user") if key_filename is None: key_filename = config.get("identityfile") if hostkey_verify: userknownhostsfile = config.get("userknownhostsfile") if userknownhostsfile: self.load_known_hosts(os.path.expanduser(userknownhostsfile)) if timeout is None: timeout = config.get("connecttimeout") if timeout: timeout = int(timeout) if username is None: username = getpass.getuser() if sock_fd is None: proxycommand = config.get("proxycommand") if proxycommand: self.logger.debug("Configuring Proxy. %s", proxycommand) if not isinstance(proxycommand, six.string_types): proxycommand = [os.path.expanduser(elem) for elem in proxycommand] else: proxycommand = os.path.expanduser(proxycommand) sock = paramiko.proxy.ProxyCommand(proxycommand) else: for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: sock = socket.socket(af, socktype, proto) sock.settimeout(timeout) except socket.error: continue try: if bind_addr: sock.bind((bind_addr, 0)) sock.connect(sa) except socket.error: sock.close() continue break else: raise SSHError("Could not open socket to %s:%s" % (host, port)) else: if sys.version_info[0] < 3: s = socket.fromfd(int(sock_fd), socket.AF_INET, socket.SOCK_STREAM) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, _sock=s) else: sock = socket.fromfd(int(sock_fd), socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) self._transport = paramiko.Transport(sock) self._transport.set_log_channel(logger.name) if config.get("compression") == 'yes': self._transport.use_compression() if hostkey_b64: # If we need to connect with a specific hostkey, negotiate for only its type hostkey_obj = None for key_cls in [paramiko.DSSKey, paramiko.Ed25519Key, paramiko.RSAKey, paramiko.ECDSAKey]: try: hostkey_obj = key_cls(data=base64.b64decode(hostkey_b64)) except paramiko.SSHException: # Not a key of this type - try the next pass if not hostkey_obj: # We've tried all known host key types and haven't found a suitable one to use - bail raise SSHError("Couldn't find suitable paramiko key class for host key %s" % hostkey_b64) self._transport._preferred_keys = [hostkey_obj.get_name()] elif self._host_keys: # Else set preferred host keys to those we possess for the host # (avoids situation where known_hosts contains a valid key for the host, but that key type is not selected during negotiation) known_host_keys_for_this_host = self._host_keys.lookup(host) or {} host_port = '[%s]:%s' % (host, port) known_host_keys_for_this_host.update(self._host_keys.lookup(host_port) or {}) if known_host_keys_for_this_host: self._transport._preferred_keys = [x.key.get_name() for x in known_host_keys_for_this_host._entries] # Connect try: self._transport.start_client() except paramiko.SSHException as e: raise SSHError('Negotiation failed: %s' % e) server_key_obj = self._transport.get_remote_server_key() fingerprint = _colonify(hexlify(server_key_obj.get_fingerprint())) if hostkey_verify: is_known_host = False # For looking up entries for nonstandard (22) ssh ports in known_hosts # we enclose host in brackets and append port number known_hosts_lookups = [host, '[%s]:%s' % (host, port)] if hostkey_b64: # If hostkey specified, remote host /must/ use that hostkey if(hostkey_obj.get_name() == server_key_obj.get_name() and hostkey_obj.asbytes() == server_key_obj.asbytes()): is_known_host = True else: # Check known_hosts is_known_host = any(self._host_keys.check(lookup, server_key_obj) for lookup in known_hosts_lookups) if not is_known_host and not unknown_host_cb(host, fingerprint): raise SSHUnknownHostError(known_hosts_lookup[0], fingerprint) # Authenticating with our private key/identity if key_filename is None: key_filenames = [] elif isinstance(key_filename, (str, bytes)): key_filenames = [key_filename] else: key_filenames = key_filename self._auth(username, password, key_filenames, allow_agent, look_for_keys) self._connected = True # there was no error authenticating self._closing.clear() # TODO: leopoul: Review, test, and if needed rewrite this part subsystem_names = self._device_handler.get_ssh_subsystem_names() for subname in subsystem_names: self._channel = self._transport.open_session() self._channel_id = self._channel.get_id() channel_name = "%s-subsystem-%s" % (subname, str(self._channel_id)) self._channel.set_name(channel_name) try: self._channel.invoke_subsystem(subname) except paramiko.SSHException as e: self.logger.info("%s (subsystem request rejected)", e) handle_exception = self._device_handler.handle_connection_exceptions(self) # Ignore the exception, since we continue to try the different # subsystem names until we find one that can connect. # have to handle exception for each vendor here if not handle_exception: continue self._channel_name = self._channel.get_name() self._post_connect() # for further upcoming RPC responses, vendor can chose their # choice of parser. Say DOM or SAX self.parser = self._device_handler.get_xml_parser(self) return raise SSHError("Could not open connection, possibly due to unacceptable" " SSH subsystem name.")
import paramiko private_key = paramiko.RSAKey.from_private_key_file( "D:\Python_Workspace\sshconnection\id_rsa") transport = paramiko.Transport(('192.168.43.127', 22)) transport.connect(username='******', pkey=private_key) ssh = paramiko.SSHClient() ssh._transport = transport stdin, stdout, stderr = ssh.exec_command("df -h") for x in stdout: print(x, end='') ssh.close()
def configure_cluster(self, nodes=None, host_template="", reconfigure=True): ## Check installation and print errors for nodes that do not exist/ ## can not connect/have incorrect installed versions and/or paths hosts = open('/tmp/hosts', 'w') masters = open('/tmp/masters', 'w') slaves = open('/tmp/slaves', 'w') # copy necessary templates to /tmp to alter them shutil.copy("./templates/hadoop/core-site.xml", "/tmp/core-site.xml") shutil.copy("./templates/hadoop/mapred-site.xml", "/tmp/mapred-site.xml") shutil.copy("./templates/hadoop/hdfs-site.xml", "/tmp/hdfs-site.xml") shutil.copy("./templates/hbase/hbase-site.xml", "/tmp/hbase-site.xml") shutil.copy("./templates/hadoop/hadoop-metrics.properties", "/tmp/hadoop-metrics.properties") shutil.copy("./templates/hbase/hadoop-metrics.properties", "/tmp/hbase.hadoop-metrics.properties") shutil.copy("./templates/hbase/hbase-env.sh","/tmp/hbase-env.sh") shutil.copy("./templates/hbase/hadoop-env.sh","/tmp/hadoop-env.sh") # core_site = open('/tmp/core-site.xml', 'rw') # mapred_site = open('/tmp/mapred-site.xml', 'rw') # hbase_site = open('/tmp/hbase-site.xml', 'rw') core_site = '/tmp/core-site.xml' mapred_site = '/tmp/mapred-site.xml' hbase_site = '/tmp/hbase-site.xml' hadoop_properties = "/tmp/hadoop-metrics.properties" hbase_properties = "/tmp/hbase.hadoop-metrics.properties" i = 0 hosts.write("127.0.0.1\tlocalhost\n") for node in nodes: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.my_logger.debug("Starting config for node: " + node.public_dns_name) ssh.connect(node.public_dns_name, username='******', password='******') ## Check for installation dirs, otherwise exit with error message stderr_all = [] stdin, stdout, stderr = ssh.exec_command('ls /opt/hadoop-0.20.2/') stderr_all.append(stderr.readlines()) stdin, stdout, stderr = ssh.exec_command('ls /opt/hbase-0.20.6/') stderr_all.append(stderr.readlines()) stdin, stdout, stderr = ssh.exec_command('echo "root - nofile 200000" >> /etc/security/limits.conf') stderr_all.append(stderr.readlines()) stdin, stdout, stderr = ssh.exec_command('swapoff -a -v') for stderr in stderr_all: if len(stderr) > 0 : self.my_logger.debug("ERROR - some installation files are missing") return if i==0: # Add the master to the /etc/hosts file hosts.write(node.private_dns_name + "\t" + host_template+"master\n") # Add the master to the masters file masters.write(host_template+"master\n") # Set hostname on the machine stdin, stdout, stderr = ssh.exec_command('echo \"'+host_template+"master\" > /etc/hostname") stdin, stdout, stderr = ssh.exec_command('hostname \"'+host_template+"master\"") for line in fileinput.FileInput(core_site,inplace=1): line = line.replace("NAMENODE_IP",host_template+"master").strip() print(line) for line in fileinput.FileInput(hbase_site,inplace=1): line = line.replace("NAMENODE_IP",host_template+"master").strip() print(line) for line in fileinput.FileInput(mapred_site,inplace=1): line = line.replace("JOBTRACKER_IP",host_template+"master").strip() print(line) for line in fileinput.FileInput(hadoop_properties,inplace=1): line = line.replace("GMETADHOST_IP",host_template+"master").strip() print(line) for line in fileinput.FileInput(hbase_properties,inplace=1): line = line.replace("GMETADHOST_IP",host_template+"master").strip() print(line) ## create namenode/datanode dirs stdin, stdout, stderr = ssh.exec_command('mkdir /opt/hdfsnames/') # Add node to cluster self.cluster[host_template+"master"] = node else: # Make a /etc/hosts file as you go hosts.write(node.private_dns_name + "\t" + host_template + str(i) +"\n") # Add all to the slaves file slaves.write(host_template+ str(i)+"\n") # Set hostname on the machine stdin, stdout, stderr = ssh.exec_command('echo \"'+host_template+str(i)+"\" > /etc/hostname") stdin, stdout, stderr = ssh.exec_command('hostname \"'+host_template+str(i)+"\"") ## create namenode/datanode dirs stdin, stdout, stderr = ssh.exec_command('mkdir /opt/hdfsdata/') # Add node to cluster self.cluster[host_template+ str(i)] = node ssh.close() # Save all collected known keys ssh.get_host_keys().save(("/tmp/known_hosts_"+str(i))) # Increase i i = i+1 # Decrase to have the last node in i i = i-1 # Add the last node to the masters file (secondary namenode) masters.write(host_template+ str(i)+"\n") ## make the quorum if self.quorum=="": # self.quorum = host_template+"master,"+host_template+str((int(self.utils.initial_cluster_size)/2))+","+host_template+str(int(self.utils.initial_cluster_size)-1) self.quorum = host_template+"master" for line in fileinput.FileInput(hbase_site,inplace=1): line = line.replace("ZK_QUORUM_IPs", self.quorum ).strip() print(line) hosts.close() masters.close() slaves.close() key_template_path="./templates/ssh_keys" ## Copy standard templates and name each node accordingly for node in nodes: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(node.public_dns_name, username='******', password='******') ## Enlarge the user limit on open file descriptors ## (workaround for HDFS-127:http://wiki.apache.org/hadoop/Hbase/Troubleshooting#A7) stdin, stdout, stderr = ssh.exec_command('ulimit -HSn 32768') transport = paramiko.Transport((node.public_dns_name, 22)) transport.connect(username = '******', password = '******') transport.open_channel("session", node.public_dns_name, "localhost") sftp = paramiko.SFTPClient.from_transport(transport) # Copy private and public key sftp.put( key_template_path+"/id_rsa","/root/.ssh/id_rsa") sftp.put( key_template_path+"/id_rsa.pub", "/root/.ssh/id_rsa.pub") sftp.put( key_template_path+"/config", "/root/.ssh/config") ## Change permissions for private key stdin, stdout, stderr = ssh.exec_command('chmod 0600 /root/.ssh/id_rsa') # Add public key to authorized_keys stdin, stdout, stderr = ssh.exec_command('cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys') # print stdout.readlines() # Copy files (/etc/hosts, masters, slaves and conf templates) removing empty lines sftp.put( "/tmp/hosts", "/etc/hosts") os.system("sed -i '/^$/d' /tmp/core-site.xml") sftp.put( "/tmp/core-site.xml","/opt/hadoop-0.20.2/conf/core-site.xml") os.system("sed -i '/^$/d' /tmp/mapred-site.xml") sftp.put( "/tmp/mapred-site.xml","/opt/hadoop-0.20.2/conf/mapred-site.xml") os.system("sed -i '/^$/d' /tmp/hdfs-site.xml") sftp.put( "/tmp/hdfs-site.xml","/opt/hadoop-0.20.2/conf/hdfs-site.xml") sftp.put( "/tmp/masters", "/opt/hadoop-0.20.2/conf/masters") sftp.put( "/tmp/slaves", "/opt/hadoop-0.20.2/conf/slaves") os.system("sed -i '/^$/d' /tmp/hbase-site.xml") sftp.put( "/tmp/hbase-site.xml", "/opt/hbase-0.20.6/conf/hbase-site.xml") sftp.put( "/tmp/slaves", "/opt/hbase-0.20.6/conf/regionservers") os.system("sed -i '/^$/d' /tmp/hadoop-metrics.properties") sftp.put( "/tmp/hadoop-metrics.properties", "/opt/hadoop-0.20.2/conf/hadoop-metrics.properties") os.system("sed -i '/^$/d' /tmp/hbase.hadoop-metrics.properties") sftp.put( "/tmp/hbase.hadoop-metrics.properties", "/opt/hbase-0.20.6/conf/hadoop-metrics.properties") sftp.put( "/tmp/hbase-env.sh", "/opt/hbase-0.20.6/conf/hbase-env.sh") sftp.put( "/tmp/hadoop-env.sh", "/opt/hadoop-0.20.2/conf/hadoop-env.sh") sftp.close() ssh.close() self.host_template = host_template ## Manipulate known hosts to make a good file known_hosts_name = '/tmp/known_hosts' known_hosts = open(known_hosts_name, 'w') j = 0 while j <= i: loop = open('/tmp/known_hosts_'+str(j), 'r') for fileLine in loop.readlines(): known_hosts.write(fileLine.strip() + "\n") loop.close() os.system("sed -i '/^$/d' /tmp/known_hosts") j = j + 1 known_hosts.close() for (clusterkey, clusternode) in list(self.cluster.items()): for line in fileinput.FileInput(known_hosts_name,inplace=1): line = line.replace(clusternode.public_dns_name, clusterkey).strip() print(line) # print clusterkey, clusternode.public_dns_name ## Upload perfect file for node in nodes: transport = paramiko.Transport((node.public_dns_name, 22)) transport.connect(username = '******', password = '******') transport.open_channel("session", node.public_dns_name, "localhost") sftp = paramiko.SFTPClient.from_transport(transport) os.system("sed -i '/^$/d' /tmp/known_hosts_"+str(j)) sftp.put( "/tmp/known_hosts", "/root/.ssh/known_hosts") sftp.close() ## Format namenode on the master ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(self.cluster[host_template+"master"].public_dns_name, username='******', password='******') if not reconfigure: ## format the namenode (all previous data will be lost!!! stdin, stdout, stderr = ssh.exec_command('echo "Y" | /opt/hadoop-0.20.2/bin/hadoop namenode -format') self.my_logger.debug("Namenode formatted:" + str(stderr.readlines())) ssh.close() ## Save to database self.utils.add_to_cluster_db(self.cluster, self.cluster_id) ## Now you should be ok, so return the nodes with hostnames return self.cluster
SSHClient()的使用代码: import paramiko ssh = paramiko.SSHClient() # 创建SSH对象 # 允许连接不在know_hosts文件中的主机 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器 ssh.connect(hostname='10.0.100.1', port=22, username='******', password='******') stdin, stdout, stderr = ssh.exec_command('ls') # 执行命令 result = stdout.read() # 获取命令结果 print(str(result, encoding='utf-8')) ssh.close() # 关闭连接 import paramiko tran = paramiko.Transport(('xx.xx.xx.xx', 22)) tran.connect(username="******", password='******') sftp = paramiko.SFTPClient.from_transport(tran) localpath = "./your_name_szj.log" remotepath = "/root/platform/your_name.log" sftp.get(remotepath, localpath) tran.close() import paramiko hostname = "10.0.100.1" port = 22 username = "******" password = "******" client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def run(bind_host, user, service): # setup logging path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) paramiko.util.log_to_file(os.path.join(path, 'log', 'ssh.log')) username = bind_host.remote_user.username port = bind_host.host.port hostname = bind_host.host.ip # now connect try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hostname, port)) except Exception as e: print('*** Connect failed: ' + str(e)) traceback.print_exc() sys.exit(1) try: t = paramiko.Transport(sock) try: t.start_client() except paramiko.SSHException: print('*** SSH negotiation failed.') sys.exit(1) try: keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) except IOError: print('*** Unable to open host keys file') keys = {} if bind_host.remote_user.auth_type == 'ssh-key': # check server's host key -- this is important. key = t.get_remote_server_key() if hostname not in keys: print('*** WARNING: Unknown host key!') elif key.get_name() not in keys[hostname]: print('*** WARNING: Unknown host key!') elif keys[hostname][key.get_name()] != key: print('*** WARNING: Host key has changed!!!') sys.exit(1) else: print('*** Host key OK.') agent_auth(t, username) if not t.is_authenticated(): manual_auth(bind_host, t) if not t.is_authenticated(): print('*** Authentication failed. :(') t.close() sys.exit(1) chan = t.open_session() chan.get_pty() chan.invoke_shell() print('*** Here we go!\n') service.log(user, bind_host, 'login') interactive.interactive_shell(chan, user, bind_host, service) chan.close() t.close() except Exception as e: print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e)) traceback.print_exc() try: t.close() except: pass sys.exit(1)
#!/usr/bin/env python3 import paramiko import os import getpass t = paramiko.Transport("10.10.2.3", 22) t.connect(username="******", password=getpass.getpass()) sftp = paramiko.SFTPClient.from_transport(t) sftp.put("firstpasswd.py", "firstpasswd.py") sftp.close()
# import paramiko # # # 创建SSH对象 # ssh = paramiko.SSHClient() # # 允许连接不在know_hosts文件中的主机 # ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # # 连接服务器 # ssh.connect(hostname='106.74.230.135', port=22101, username='******', password='******') # # # 执行命令 # stdin, stdout, stderr = ssh.exec_command('df') # # 获取命令结果 # result = stdout.read() # print(result.decode('utf-8')) # # 关闭连接 # ssh.close() import paramiko transport = paramiko.Transport(('106.74.230.135', 22101)) transport.connect(username='******', password='******') sftp = paramiko.SFTPClient.from_transport(transport) # 将location.py 上传至服务器 /tmp/test.py sftp.put(r'D:\video\python20期\day9\02 多线程\7 GIL测试.py', '/root/test.txt') # 将remove_path 下载到本地 local_path # sftp.get('remove_path', 'local_path') transport.close()
def interactive_shell(self): """Open an interactive TTY shell. The code in this method was generously provided by our friends at StarCluster (http://star.mit.edu/cluster/) """ try: addrinfo = socket.getaddrinfo(self.ssh._host, self.ssh._port, socket.AF_UNSPEC, socket.SOCK_STREAM) for (family, socktype, proto, canonname, sockaddr) in addrinfo: if socktype == socket.SOCK_STREAM: af = family break else: raise exception.SSHError( 'No suitable address family for %s' % self.ssh._host) sock = socket.socket(af, socket.SOCK_STREAM) sock.settimeout(self.timeout) sock.connect((self.ssh._host, self.ssh._port)) transport = paramiko.Transport(sock) transport.banner_timeout = self.timeout except socket.error: raise exception.SSHConnectionError(self.ssh._host, self.ssh._port) try: transport.connect(username=self.ssh._username, pkey=self.ssh._pkey, password=self.ssh._password) except paramiko.AuthenticationException: raise exception.SSHAuthException(self.ssh._username, self.ssh._host) except paramiko.SSHException as e: msg = e.args[0] raise exception.SSHError(msg) except socket.error: raise exception.SSHConnectionError(self.ssh._host, self.ssh._port) except EOFError: raise exception.SSHConnectionError(self.ssh._host, self.ssh._port) except Exception as e: raise exception.SSHError(str(e)) try: sftp = paramiko.SFTPClient.from_transport(transport) assert sftp is not None sftp.close() except paramiko.SFTPError as e: if 'Garbage packet received' in str(e): lgr.debug("Garbage packet received", exc_info=True) raise exception.SSHAccessDeniedViaAuthKeys(self.ssh._username) raise chan = transport.open_session() chan.get_pty(self.term, self.cols, self.lines) chan.invoke_shell() oldtty = termios.tcgetattr(sys.stdin) try: tty.setraw(sys.stdin.fileno()) tty.setcbreak(sys.stdin.fileno()) chan.settimeout(0.0) while True: r, w, e = select.select([chan, sys.stdin], [], []) if chan in r: try: x = chan.recv(1024) if len(x) == 0: break sys.stdout.write(x.decode('utf-8')) sys.stdout.flush() except socket.timeout: pass if sys.stdin in r: # Fixes up arrow problem x = os.read(sys.stdin.fileno(), 1) if len(x) == 0: break chan.send(x) finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty) chan.close()
def connect_to(self, Host, Username = '******', Password = '******', Port = 22): self.transport = paramiko.Transport((Host, Port)) self.transport.connect(username = Username, password = Password) self.ftp = paramiko_sftp_client.from_transport(self.transport) self.ftp.go_to_home(Username)
#!/usr/bin/env python import sys, paramiko if len(sys.argv) < 5: print "args missing" sys.exit(1) hostname = sys.argv[1] password = sys.argv[2] source = sys.argv[3] dest = sys.argv[4] username = "******" port = 22 try: t = paramiko.Transport((hostname, port)) t.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(t) sftp.get(source, dest) finally: t.close()
def remoterealhost(): remoteserver.start() ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname='127.0.0.1', port=remoteserver.local_bind_port, username=Remote_User, password=Remote_Pass) #stdin, stdout, stderr = ssh.exec_command('ls ' + Remote_file_path) #exec_command返回的为tunple,第二个为stdout if ssh.exec_command('ls ' + Remote_file_path)[1].read(): if ssh.exec_command(service_command)[1].read(): stdin, stdout, stderr = ssh.exec_command('cp -r ' + Remote_file_path + ' ' + Remote_bak_path + Ser_name + '_' + now_time) print(stdout.read()) scp = paramiko.Transport( ('127.0.0.1', remoteserver.local_bind_port)) scp.connect(username=Remote_User, password=Remote_Pass) sftp = paramiko.SFTPClient.from_transport(scp) sftp.put(Local_War, Remote_upload_file) sftp.close() ssh.exec_command('kill -9 ' + ssh.exec_command(pid_command)[1].read()) stdin, stdout, stderr = ssh.exec_command('rm -rf ' + Remote_file_path + '*') stdin, stdout, stderr = ssh.exec_command('mv ' + Remote_upload_file + ' ' + Remote_file_war) print(stdout.read()) else: ssh.exec_command('cp -r ' + Remote_file_path + ' ' + Remote_bak_path + Ser_name + '_' + now_time) scp = paramiko.Transport( ('127.0.0.1', remoteserver.local_bind_port)) scp.connect(username=Remote_User, password=Remote_Pass) sftp = paramiko.SFTPClient.from_transport(scp) sftp.put(Local_War, Remote_upload_file) sftp.close() stdin, stdout, stderr = ssh.exec_command('rm -rf ' + Remote_file_path + '*') stdin, stdout, stderr = ssh.exec_command('mv ' + Remote_upload_file + ' ' + Remote_file_war) print(stdout.read()) else: print('the war path not exist,please login server checkout') ###service check#### ##service check#### if ssh.exec_command(service_command)[1].read(): logging.warn("the tomcat8080 service is running, need to restart") ssh.exec_command('kill -9 ' + ssh.exec_command(pid_command)[1].read()) stdin, stdout, stderr = ssh.exec_command( 'source /etc/profile && /bin/bash ' + tomcat_bin_path) print(stdout.read()) else: logging.warn("the tomcat8080 service stop, to start tomcats") stdin, stdout, stderr = ssh.exec_command( 'source /etc/profile && /bin/bash ' + tomcat_bin_path) print(stdout.read()) ssh.close() remoteserver.close()
import os import sys import paramiko #文件传输链接 t = paramiko.Transport('10.2.1.64', 22) t.connect(username='******', password='******') #传输文件 sftp = paramiko.SFTPClient.from_transport(t) #from to sftp.put('test.logs', '/Users/students/test_log.log') t.close() # # sftp.get('/Users/canvas/test_log.log', 'log2.log') # t.close()
def make_ssh_server_connection(conn, socket_options, none_auth=False, password_auth=None): log("make_ssh_server_connection%s", (conn, socket_options, none_auth, password_auth)) ssh_server = SSHServer(none_auth=none_auth, password_auth=password_auth) DoGSSAPIKeyExchange = False sock = conn._socket t = None def close(): if t: log("close() closing %s", t) try: t.close() except Exception: log("%s.close()", t, exc_info=True) log("close() closing %s", conn) try: conn.close() except Exception: log("%s.close()", conn) try: t = paramiko.Transport(sock, gss_kex=DoGSSAPIKeyExchange) gss_host = socket_options.get("ssh-gss-host", socket.getfqdn("")) t.set_gss_host(gss_host) #load host keys: PREFIX = "ssh_host_" SUFFIX = "_key" host_keys = {} def add_host_key(fd, f): ff = os.path.join(fd, f) keytype = f[len(PREFIX):-len(SUFFIX)] if not keytype: log.warn("Warning: unknown host key format '%s'", f) return False keyclass = getattr(paramiko, "%sKey" % keytype.upper(), None) if keyclass is None: #Ed25519Key keyclass = getattr( paramiko, "%s%sKey" % (keytype[:1].upper(), keytype[1:]), None) if keyclass is None: log("key type %s is not supported, cannot load '%s'", keytype, ff) return False log("loading %s key from '%s' using %s", keytype, ff, keyclass) try: host_key = keyclass(filename=ff) if host_key not in host_keys: host_keys[host_key] = ff t.add_server_key(host_key) return True except IOError as e: log("cannot add host key '%s'", ff, exc_info=True) except paramiko.SSHException as e: log("error adding host key '%s'", ff, exc_info=True) log.error("Error: cannot add %s host key '%s':", keytype, ff) log.error(" %s", e) return False host_key = socket_options.get("ssh-host-key") if host_key: d, f = os.path.split(host_key) if f.startswith(PREFIX) and f.endswith(SUFFIX): add_host_key(d, f) if not host_keys: log.error("Error: failed to load host key '%s'", host_key) close() return None else: ssh_key_dirs = get_ssh_conf_dirs() log("trying to load ssh host keys from: %s", csv(ssh_key_dirs)) for d in ssh_key_dirs: fd = osexpand(d) log("osexpand(%s)=%s", d, fd) if not os.path.exists(fd) or not os.path.isdir(fd): log("ssh host key directory '%s' is invalid", fd) continue for f in os.listdir(fd): if f.startswith(PREFIX) and f.endswith(SUFFIX): add_host_key(fd, f) if not host_keys: log.error("Error: cannot start SSH server,") log.error(" no readable SSH host keys found in:") log.error(" %s", csv(ssh_key_dirs)) close() return None log("loaded host keys: %s", tuple(host_keys.values())) t.start_server(server=ssh_server) except (paramiko.SSHException, EOFError) as e: log("failed to start ssh server", exc_info=True) log.error("Error handling SSH connection:") log.error(" %s", e) close() return None try: chan = t.accept(SERVER_WAIT) if chan is None: log.warn("Warning: SSH channel setup failed") #prevent errors trying to access this connection, now likely dead: conn.set_active(False) close() return None except paramiko.SSHException as e: log("failed to open ssh channel", exc_info=True) log.error("Error opening channel:") log.error(" %s", e) close() return None log("client authenticated, channel=%s", chan) ssh_server.event.wait(SERVER_WAIT) log("proxy channel=%s", ssh_server.proxy_channel) if not ssh_server.event.is_set() or not ssh_server.proxy_channel: from xpra.net.bytestreams import pretty_socket log.warn("Warning: timeout waiting for xpra SSH subcommand,") log.warn(" closing connection from %s", pretty_socket(conn.target)) close() return None log("client authenticated, channel=%s", chan) return SSHSocketConnection(ssh_server.proxy_channel, sock, conn.local, conn.endpoint, conn.target, socket_options=socket_options)