def update_server(): server_count = 0 server_list = LinuxServer.objects.filter(decommissioned=False) for server in server_list: if utilities.ping(server): client = SSHClient() if utilities.ssh(server, client): command = 'adquery user | grep ctesta' stdin, stdout, stderr = client.exec_command(command) try: exists = stdout.readlines()[0].rstrip() print '--------------------' print server.name print exists server_count = server_count + 1 command2 = 'ls -l /home | grep ctesta' stdin, stdout, stderr = client.exec_command(command2) try: exists2 = stdout.readlines()[0].rstrip() print exists2 except: print 'No home directory' except: continue print "Total number of Linux servers: " + str(server_count)
def make_queen_bee(hostname, username, key_filename): client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect( hostname, username=username, key_filename=key_filename ) _, stdout, sterr = client.exec_command('sudo pkill shutdown') print(stdout.read() + sterr.read()) boto_path = path.expanduser('~/.boto') command = 'scp -o "StrictHostKeyChecking=no" -i {} {} {}@{}:~/.boto'.format( key_filename, boto_path, username, hostname ) system(command) print(command) command = 'scp -o "StrictHostKeyChecking=no" -i {} {} {}@{}:~/.ssh/'.format( key_filename, key_filename, username, hostname ) system(command) print(command) # the royal yaass _, stdout, _ = client.exec_command('touch ~/.yaass') client.close() return hostname
def main(): logging.basicConfig(level=logging.INFO) if isfile(get_config_path(__file__, '/esxi.ini')): config = ConfigurationINI(get_config_path(__file__, '/esxi.ini')) elif isfile('/etc/esxi.ini'): config = ConfigurationINI('/etc/esxi.ini') else: logging.critical('/etc/esxi.ini missing.') exit(0) logging.debug('Configuration file used : {conf}'.format(conf=get_config_path(__file__, '/esxi.ini'))) try: ssh = SSHClient() ssh.set_missing_host_key_policy(AutoAddPolicy()) ssh.connect(config['esxi']['hostip'], username=config['esxi']['username'], password=config['esxi']['password']) except SocketError as e: logging.critical('Host unreachable.') logging.critical(e.__str__()) exit() logging.info('vim-cmd hostsvc/firmware/sync_config') ssh.exec_command('vim-cmd hostsvc/firmware/sync_config') logging.info('vim-cmd hostsvc/firmware/backup_config') stdin, stdout, stderr = ssh.exec_command('vim-cmd hostsvc/firmware/backup_config') for l in stdout: m = search('http://\*(.*)', l.strip()) if m is not None: download = "http://{host}{position}".format( host=config['esxi']['hostip'], position=m.group(1) ) logging.info("Downloading {0}".format(download)) local_file = '{localpath}/backup-{host}-{date}.tgz'.format( host=config['esxi']['hostdns'], date=strftime(config['local']['dateformat']), localpath=config['local']['savepath'] ) urlretrieve(download, local_file) if config['webdav']['enabled']: logging.info("Uploading file on WebDAV") comediaoc = webdav_connect( config['webdav']['host'], username=config['webdav']['username'], password=config['webdav']['password'], protocol=config['webdav']['proto'], verify_ssl=False ) comediaoc.upload(local_file, '{0}/backup-{1}-{2}.tgz'.format( config['webdav']['savepath'], config['esxi']['hostdns'], strftime(config['local']['dateformat']) )) ssh.close()
def copy(hostname, username, filepath, remotefile): ssh = SSHClient() # ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname, username=username) ssh.exec_command("mkdir -p " + remotefile[0:remotefile.rindex('/')]) # SCPCLient takes a paramiko get_transportt as its only argument scp = SCPClient(ssh.get_transport()) scp.put(filepath, remotefile)
def _setControlState(self,state): if state == False: client = SSHClient() client.load_system_host_keys() client.connect(** self.sshArgs) #stdin, stdout, stderr = client.exec_command('ls -l') client.exec_command('shutdown now') client.close() return
class SSHLatentBuildSlave(AbstractLatentBuildSlave): """ Build slave that runs a command over SSH to start and stop the build slave. """ def __init__(self, name, password, ssh_host, username, key_path, host_key_file=os.path.expanduser("~/.ssh/known_hosts"), **kwargs): """ Creates a new SSH latent build slave with the given parameters. """ AbstractLatentBuildSlave.__init__(self, name, password, **kwargs) self.client = SSHClient() self.client.load_system_host_keys(host_key_file) self.hostname = ssh_host self.username = username self.key_path = key_path self.started = False def is_connected(self): self.client.get_transport() != None and self.client.get_transport().is_active() def start_instance(self, build): if self.started: raise ValueError('already started') return threads.deferToThread(self._start_instance) def _start_instance(self): log.msg("connecting to SSH server") self.client.connect(self.hostname, username=self.username, key_filename=self.key_path) self.client.get_transport().set_keepalive(True) log.msg("executing start command") stdin, stdout, stderr = self.client.exec_command("~/bbvenv/bin/env_exec buildslave start ~/bbslave") self.started = True return True def stop_instance(self, fast=False): if not self.started: return defer.succeed(None) return self._stop_instance() def _stop_instance(self): if not self.is_connected(): self.client.connect(self.hostname, username=self.username, key_filename=self.key_path) log.msg("stopping build slave") self.client.exec_command("~/bbvenv/bin/env_exec buildslave stop ~/bbslave") log.msg("closing connection") self.client.close() log.msg("finished") self.started = False def buildFinished(self, sb): log.msg("finished build. insubstantiating") self.insubstantiate()
def scale_out_container(server, image_name, args, count): client = SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.load_system_host_keys() client.connect(server[0], username=server[1], password=server[2]) name_list = get_container_list(server, image_name) diff = count - len(name_list) if diff > 0: for i in range(diff): stdin, stdout, stderr = client.exec_command('sudo docker -H tcp://0.0.0.0:2376 run %s %s' % (args, image_name)) elif diff < 0: for i in range(-diff): stdin, stdout, stderr = client.exec_command('sudo docker -H tcp://0.0.0.0:2376 rm -f %s' % name_list[i]) client.close()
def put_file_on_target(self, ip, file_name): """ SSH to a host and touch a file there. We can later check for this files existence to determine whether a kickstart completed successfully. :param ip: (string) IP address of host :param file_name: name of file to create :return: """ ssh = SSHClient() ssh.set_missing_host_key_policy(AutoAddPolicy()) # wont require saying 'yes' to new fingerprint ssh.connect(ip, username=self.ssh_user, password=self.ssh_password) ssh.exec_command('touch ' + file_name) ssh.close() return
def main(): client = SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.load_system_host_keys() client.connect("localhost", username="******") stdin, stdout, stderr = client.exec_command('python /home/ubuntu/fsync/fsync/utils/rpc_server.py /home/ubuntu/test1/test1 8081 > /dev/null 2>&1 &') while not stdout.channel.exit_status_ready(): continue stdin, stdout, stderr = client.exec_command('python /home/ubuntu/fsync/fsync/utils/rpc_server.py /home/ubuntu/test2/test2 8082 > /dev/null 2>&1 &') while not stdout.channel.exit_status_ready(): continue
def update_server(server): if utilities.ping(server): client = SSHClient() if utilities.ssh(server, client): print server.name command = 'python -V' stdin, stdout, stderr = client.exec_command(command) # https://bugs.python.org/issue18338 # Apparently this is an old bug and only fixed in Python 3.4 and 2.7 # where the version is sent to stderr try: version = stderr.readlines()[0].rstrip() version = re.sub('Python ', '', version) except: version = 'None' if version == 'None': try: version = stdout.readlines()[0].rstrip() version = re.sub('Python ', '', version) except: version = 'None' print version # check existing value, if it exists, don't update if str(version) != str(server.python): utilities.log_change(server, 'python', str(server.python), str(version)) LinuxServer.objects.filter(name=server).update(python=version, modified=timezone.now()) client.close()
def update_server(server): if utilities.ping(server): client = SSHClient() if utilities.ssh(server, client): print server.name command = 'lslpp -L | grep -i imper' stdin, stdout, stderr = client.exec_command(command) test = stdout.readlines() try: output = test[0].rstrip() imperva_version = ' '.join(output.split()) imperva_version = imperva_version.split(" ")[1].rstrip() print imperva_version # check existing value, if it exists, don't update if str(imperva_version) != str(server.imperva): utilities.log_change(server, 'Imperva', str(server.imperva), str(imperva_version)) AIXServer.objects.filter(name=server).update(imperva=imperva_version, modified=timezone.now()) except: imperva_version = 'None' print imperva_version if str(imperva_version) != str(server.imperva): utilities.log_change(server, 'Imperva', str(server.imperva), str(imperva_version)) AIXServer.objects.filter(name=server).update(imperva=imperva_version, modified=timezone.now())
def start_monitor(self): local_name = platform.node() print "Starting Cassandra Monitor for %s" % self.server while True: try: ssh = SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(AutoAddPolicy()) ssh.connect(self.server, timeout=5, allow_agent=False) stdin, stdout, stderr = ssh.exec_command(CASS_CMD) stdin.close() for line in stdout: # Any line that shows up will be a downed server # server datacenter rack status state load owns token downed_node = line.split() raise DownedNodeException(downed_node[0]) stdout.close() err = stderr.read() if err: raise Exception("Unknown error: %s" % str) stderr.close() ssh.close() except DownedNodeException as e: self.mark_error(e.node, e) except SSHException as e: self.mark_error(self.server, "%s could not connect to %s: %s" % (local_name, self.server, e)) except Exception as e: self.mark_error(local_name, "Unknown error: %s" % e) else: self.clear_error() time.sleep(INTERVAL)
def update_server(server): if utilities.ping(server): client = SSHClient() if utilities.ssh(server, client): my_output = False command = 'lspv | grep ASM | uniq' stdin, stdout, stderr = client.exec_command(command) output = stdout.readlines() for line in output: line = line.rstrip() if re.search("ASM", line): my_output = True # FIXME print '--------' print server print '111111111111111111111111111' print output print '222222222222222222222222222222' print my_output print '333333333333333333333333333333' print server.asm # check existing value, if it exists, don't update if my_output != server.asm: utilities.log_change(server, 'asm', str(server.asm), str(my_output)) AIXServer.objects.filter(name=server).update(asm=my_output, modified=timezone.now())
def update_server(server): counter = 0 if utilities.ping(server): client = SSHClient() if utilities.ssh(server, client): command = 'dzdo emgr -l' stdin, stdout, stderr = client.exec_command(command) lines = stdout.readlines() print "" print "-----------------------------------" print server.name # del lines[0] # del lines[1] # del lines[2] for line in lines[3:-17]: counter = counter + 1 print line.rstrip() print "Number of efixes -> " + str(counter) # check existing value, if it exists, don't update if counter != server.efix: utilities.log_change(server, 'efix', str(server.efix), str(counter)) AIXServer.objects.filter(name=server).update(efix=counter, modified=timezone.now())
def get(nodes_file, request): """Return the logs""" args = dict(request.args.items()) try: container = args.pop('container') except KeyError: raise errors.BadRequest('No container on URL arguments') results = dict() with open(nodes_file) as f: nodes = yaml.load(f) try: rsa_key_file = nodes.pop('rsa_key') pkey = RSAKey.from_private_key_file(rsa_key_file) except Exception as e: print('Failed to read RSA Key, {} {}'.format(type(e), e)) raise ssh = SSHClient() ssh.set_missing_host_key_policy(AutoAddPolicy) cmd = 'docker logs {container} {args}'.format( container=container, args=' '.join(['--{}={}'.format(a, args[a]) for a in args])) for _, ips in nodes.items(): for ip in ips: ssh.connect(hostname=ip, username='******', pkey=pkey) print('ssh root@{ip} {cmd}'.format(ip=ip, cmd=cmd)) _in, _out, _err = ssh.exec_command(cmd) status = _out.channel.recv_exit_status() results[ip] = dict( status=status, stdout=_out.read(), stderr=_err.read()) ssh.close() return results
def run(args, logging): """ Runs the cmd executor :param args: A NameSpace object with the arguments required :param logging: A python logging object :return: An exit code """ hostname = build_data.read(args.build_id, 'instance', 'public_ip_address') client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) logging.info('Connecting to remote host "{0}"...'.format(hostname)) client.connect(hostname, port=args.port, username=args.username, key_filename=args.key_filename, timeout=args.timeout) logging.info('Executing command "{0}"...'.format(args.cmd)) # pylint: disable=W0612 stdin, stdout, stderr = client.exec_command(args.cmd) exit_code = stdout.channel.recv_exit_status() stdout = stdout.channel.makefile().read() or 'None' stderr = stderr.channel.makefile().read() or 'None' logging.info('Exit code...') logging.info(exit_code) logging.info('Standard out...') logging.info(stdout) logging.info('Standard error...') logging.info(stderr) return exit_code, stdout, stderr
class SshArchiver(Archiver): """ Archives artifacts using ssh. """ def start(self): """ Opens the ssh connection. """ self.ssh_client = SSHClient() self.ssh_client.set_missing_host_key_policy(WarningPolicy()) self.ssh_client.connect( self.target.host, pkey=self.target.ssh_credentials.get_pkey()) self.sftp_client = SFTPClient.from_transport( self.ssh_client.get_transport()) def end(self): """ Closes the ssh connection. """ self.ssh_client.close() def archive_artifact(self, artifact_url, destination): """ Uploads the artifact_url to the destination on the remote server, underneath the target's basedir. """ destination = os.path.join(self.target.basedir, destination) _, stdout, _ = self.ssh_client.exec_command( "mkdir -p `dirname %s`" % destination) # TODO: raise exception if the command fails _ = stdout.channel.recv_exit_status() # noqa artifact = urllib2.urlopen(artifact_url) self.sftp_client.stream_file_to_remote(artifact, destination)
def loginThread(self): client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) loginDetailString = self.username + "@" + self.clientip +" (" + self.password + ")" print "Attempting login with", loginDetailString try: client.connect(hostname=self.clientip, username=self.username, password=self.password) except: print "Authentication failed for", loginDetailString return sendEmail('New login success!', "Successfully logged in to remote box: " + loginDetailString) configName = "not_root_command" if (self.username == "root"): configName = "root_command" command = config().get('dirtybastard', configName)[1:-1] # Remove quotes print "SUCCESS! Running command: " + command stdin, stdout, stderr = client.exec_command(command) print "stdout:" stdoutString = "" for line in stdout.readlines(): print line.strip() stdoutString = stdoutString + line.strip() + "\n" sendEmail('Output from command', "stdout:\n" + stdoutString);
def _uploadFiles(self, dstdir, **sshargs): (yield TaskOutput(u"ENTER", OutputType.NOTIFY)) sshcli = SSHClient() sftpcli = None code = 0 try: if not (yield TaskOutput(u"Conntecting to %s ..." % sshargs["hostname"])): raise CommandTerminated() sshcli.set_missing_host_key_policy(AutoAddPolicy()) sshcli.connect(**sshargs) if not (yield TaskOutput(u"Connected, ready to upload ...")): raise CommandTerminated() ret = sshcli.exec_command("[ -d {0} ] && rm -rf {0}; mkdir -p {0}".format(dstdir)) errstr = ret[2].read() if errstr != "": raise Exception(errstr) sftpcli = sshcli.open_sftp() for f in os.listdir(self.hdiff_dir): if f.lower().endswith(".html"): localfile = os.path.join(self.hdiff_dir, f) remotefile = os.path.join(dstdir, f).replace(os.sep, "/") if not (yield TaskOutput(u"Uploading %s ..." % f)): raise CommandTerminated() sftpcli.put(localfile, remotefile) except CommandTerminated: code = -2 (yield TaskOutput(u"Uploading Terminited", OutputType.WARN)) except Exception as ex: code = -1 (yield TaskOutput(ex.message, OutputType.ERROR)) finally: if sftpcli: sftpcli.close() sshcli.close() (yield TaskOutput(u"EXIT %d" % code, OutputType.NOTIFY))
def update_server(server): if utilities.ping(server): client = SSHClient() if utilities.ssh(server, client): print '------------------------------------' print server.name command = 'dzdo /usr/sbin/smbd -V' stdin, stdout, stderr = client.exec_command(command) try: samba = stdout.readlines()[0] print samba except: samba = "None" print samba samba = re.sub(r'Version ', '', samba) # check existing value, if it exists, don't update if str(samba) != str(server.samba): utilities.log_change(server, 'samba', str(server.samba), str(samba)) LinuxServer.objects.filter(name=server).update(samba=samba, modified=timezone.now())
def update_server(): text = "======================ESB /opt Console Space Report=============\n" print text server_list = ['p1esbapp', 'p2esbapp', 'p3esbapp', 'p4esbapp', 'p5esbapp', 'p6esbapp', 'p7esbapp', 'p8esbapp', 'p9esbapp', 'p10esbapp', 'p11esbapp', 'p12esbapp'] for server in server_list: text = text + "-------------------" + str(server) + "---------------------\n" client = SSHClient() client.load_system_host_keys() client.connect(str(server), username="******") command = 'df -h | grep opt; du -csh /opt/esb/jboss-eap-4.3/jboss-as/console.log' stdin, stdout, stderr = client.exec_command(command) for output in stdout.readlines(): # print output text = text + output + '\n' print text # message = """From: Boomer <*****@*****.**> # To: Boomer <*****@*****.**> # Suject: ESB /opt console.log Report.""" + text msg = MIMEText(text) msg['Subject'] = 'ESB /opt console.log report' msg['From'] = email.utils.formataddr(('Boomer', "william.rehfield\@wellcare.com")) msg['To'] = email.utils.formataddr(('Boomer', "william.rehfield\@wellcare.com")) # s = smtplib.SMTP('localhost') # s.sendmail( server = smtplib.SMTP('mail') server.sendmail("*****@*****.**", "*****@*****.**", msg.as_string())
def update_server(server): if utilities.ping(server): client = SSHClient() if utilities.ssh(server, client): tmef = '' print "=======================" print server.name try: command = 'lparstat -i | grep "Target Memory Expansion Factor"' stdin, stdout, stderr = client.exec_command(command) tmef = stdout.readlines()[0].rstrip() tmef = tmef.split()[5] print '->>' + tmef if tmef == '-': tmef = 0.00 else: tmef = float(tmef) except: pass print "=======================" print server.name print tmef # check existing value, if it exists, don't update if str(tmef) != str(server.tmef): utilities.log_change(server, 'tmef', str(server.tmef), str(tmef)) AIXServer.objects.filter(name=server).update(tmef=tmef, modified=timezone.now())
def __init__(self, cfg, info, log_fd, log_file): super(XBuilderMirrorPlugin, self).__init__(cfg, info, log_fd, log_file) self.ssh = self.cfg['mirror'].copy() for k, v in self.ssh.items(): if not v and k != 'pkey': raise XUtilsError('[mirror plugin]: mandatory parameter \'%s\' not set.' % k) # Test SSH connection ssh = SSHClient() try: ssh.set_missing_host_key_policy(AutoAddPolicy()) ssh.connect(self.ssh['server'], username=self.ssh['user'], key_filename=self.ssh['pkey']) except BadHostKeyException: raise XUtilsError('Server host key verification failed.') except AuthenticationException: raise XUtilsError('Authentication to %s@%s failed.' % (self.ssh['user'], self.ssh['server'])) except SSHException: raise XUtilsError('Unable to establish a SSH connection to %s' % self.ssh['server']) finally: stdin, stdout, stderr = ssh.exec_command( # pylint: disable=unused-variable 'touch %s/foo && rm %s/foo' % (self.ssh['base_dir'], self.ssh['base_dir']) ) if stderr.read(): raise XUtilsError( 'User %s does not have sufficient permission on server %s to create/delete files.' % (self.ssh['user'], self.ssh['server']) ) ssh.close()
def ssh_cmd(ip, remote_cmd, user='******', password=None, quiet=False): """ @param server_ip @param user @param password @param remote_cmd @return A map based on pass / fail run info """ output = StringIO() error = StringIO() ssh = SSHClient() ssh.set_missing_host_key_policy(AutoAddPolicy()) ssh.connect(ip, username=user, password=password) stdin, stdout, stderr = ssh.exec_command(remote_cmd) stdin.close() exit_status = None for line in stdout.xreadlines(): if not quiet: sys.stdout.write(line) output.write(line) for line in stderr.xreadlines(): sys.stdout.write(line) error.write(line) exit_status = stdout.channel.recv_exit_status() return {'success': True if exit_status == 0 else False, 'return': output.getvalue(), 'exit_status': exit_status, 'error': error.getvalue()}
def ssh_cmd(ip, remote_cmd, user='******', password=None): """ @param server_ip @param user @param password @param remote_cmd @return A map based on pass / fail run info """ output = StringIO() error = StringIO() ssh = SSHClient() ssh.set_missing_host_key_policy(WarningPolicy()) ssh.connect(ip, username=user, password=password, allow_agent=False) stdin, stdout, stderr = ssh.exec_command(remote_cmd) stdin.close() for line in stdout: if util.logger < 10: sys.stdout.write(line) util.logger.info(line.strip()) output.write(line) for line in stderr: util.logger.error(line.strip()) error.write(line) exit_status = stdout.channel.recv_exit_status() ret = {'success': True if exit_status == 0 else False, 'return': output.getvalue(), 'exit_status': exit_status, 'error': error.getvalue()} return ret
class conn(): def __init__(self, user, passwd, ip): self.user = user self.passwd = passwd self.ip = ip self.sshConn = SSHClient() self.sshConn.set_missing_host_key_policy(AutoAddPolicy()) try: self.sshConn.connect(self.ip, port = 22, username = self.user,password = self.passwd, timeout = 60, allow_agent = False,look_for_keys = False) self.status = 'Succeeded' except: self.status = 'Failed' def runCommand(self, command): self.stdin, self.stdout, self.stderr = (None,None,None) if self.status == 'Succeeded': self.stdin, self.stdout, self.stderr = self.sshConn.exec_command(command) def closeSocket(self): self.sshConn.close()
def executeOnMaster(self, cmd): """ Execute command on the current master leader """ self.log.debug("Executing on master: " + cmd) if self._hostnameResolves(self.getManagementEndpoint()): ssh = SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect( self.getManagementEndpoint(), username = self.config.get('ACS', "username"), port = 2200, key_filename = os.path.expanduser(self.config.get('SSH', "privatekey"))) session = ssh.get_transport().open_session() AgentRequestHandler(session) stdin, stdout, stderr = ssh.exec_command(cmd) stdin.close() result = "" for line in stdout.read().splitlines(): self.log.debug(line) result = result + line.decode("utf-8") + "\n" for line in stderr.read().splitlines(): self.log.error(line) else: self.log.error("Endpoint " + self.getManagementEndpoint() + " does not exist, cannot SSH into it.") result = "Exception: No cluster is available at " + self.getManagementEndpoint() ssh.close() return result
def __wait_ssh_working( self ): while True: client = SSHClient( ) try: client.set_missing_host_key_policy( self.IgnorePolicy( ) ) client.connect( hostname=self.ip_address, username=self.admin_account( ), timeout=a_short_time ) stdin, stdout, stderr = client.exec_command( 'echo hi' ) try: line = stdout.readline( ) if line == 'hi\n': return else: raise AssertionError( "Read unexpected line '%s'" % line ) finally: stdin.close( ) stdout.close( ) stderr.close( ) except AssertionError: raise except KeyboardInterrupt: raise except Exception as e: logging.info( e ) finally: client.close( ) time.sleep( a_short_time )
def update_server(server): if utilities.ping(server): client = SSHClient() if utilities.ssh(server, client): print server.name # with the vio servers we want the ios.level rather than the os_level vio_servers = AIXServer.objects.filter(name__contains='vio') hmc_servers = AIXServer.objects.filter(name__contains='hmc') if server in vio_servers: command = 'cat /usr/ios/cli/ios.level' elif server in hmc_servers: command = 'lshmc -V | grep Release' else: command = 'dzdo oslevel -s' stdin, stdout, stderr = client.exec_command(command) # need rstrip() because there are extra characters at the end oslevel = stdout.readlines()[0].rstrip() if server in hmc_servers: oslevel = "HMC " + oslevel if server in vio_servers: oslevel = "VIO " + oslevel # check existing value, if it exists, don't update if str(oslevel) != str(server.os_level): utilities.log_change(server, 'oslevel', str(server.os_level), str(oslevel)) AIXServer.objects.filter(name=server, exception=False, active=True).update(os_level=oslevel, modified=timezone.now())
def __startInstance( device , datatype , response , pcount ): processorNode = settings.PROCCESSOR_NODES[ (pcount + 1 ) % len( settings.PROCCESSOR_NODES ) ] logger.debug("Creating Node On " + processorNode ) client = SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) rsa_private_key = paramiko.RSAKey.from_private_key_file( settings.SSHID ) client.connect( processorNode , username="******" , pkey = rsa_private_key ) logger.debug( 'docker run -d ' + datatype.processor + ' python /root/Processor.py ' + settings.MASTER_HOSTNAME + \ ' ' + device.identifier + ' ' + datatype.identifier + ' ' + response.identifier ) stdin, stdout, stderr = client.exec_command( 'docker run -d ' + datatype.processor + ' python /root/Processor.py ' + settings.MASTER_HOSTNAME + \ ' ' + device.identifier + ' ' + datatype.identifier + ' ' + response.identifier ) for i in stderr.readlines(): logger.error(str(i)) for i in stdout.readlines(): logger.debug(str(i)) identifier = i return { 'identifier' : identifier , 'node' : processorNode }
def init_module(self,npath, id, dev,name): try: print ("[SCP Connecting] With: ", dev.path) ssh = SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(dev.path, username='******', password='******') print ("[SSH Connected] successful") scp = SCPClient(ssh.get_transport()) print ("[SCP Connected] successful") imTag = str(uuid.uuid4().int) id = imTag[:4] ssh.exec_command('mkdir Docker' + id) print ("[SCP CLIENT] Directory created") scp.put(npath + 'run.sh','Docker' + id + '/run.sh') scp.put(npath + 'Dockerfile','Docker' + id + '/Dockerfile') print ("[SCP CLIENT] Copied files") docker_build ='docker build -t ' + imTag + ' --build-arg FILEPATH=Docker' + id + ' Docker' + id print (docker_build) ssh.exec_command(docker_build) print ("[SCP CLIENT] Docker built") ssh.exec_command('docker run --privileged ' + imTag) logging.getLogger("paramiko").setLevel(logging.WARNING) print ("[SCP CLIENT] Docker run") c = Module(modulename=name,moduleid=imTag,containerid="empty",filepath=npath,containertag=imTag,deviceid=dev,status="running") c.save() except: print ("[ERROR] ") print ("[SCP CLIENT] Could not start docker container")
def check_ssh_connection(host, port, login, password=None, timeout=5, ftpdir=None): """ Check SSH connection """ client = SSHClient() client.load_system_host_keys() ok = False ftpdir_exists = False try: client.connect(host, username=login, port=port, password=password, look_for_keys=False, allow_agent=False, timeout=timeout) ok = True except (AuthenticationException, SSHException, BadHostKeyException) as e: msg = tr('Error while connecting to SFTP server') msg += ': ' + str(e) ok = False except Exception as e: msg = tr('Error while connecting to SFTP server') msg += ': ' + str(e) ok = False finally: # Check ftpdir exists if ftpdir: ok = True try: stdin, stdout, stderr = client.exec_command( 'ls {}'.format(ftpdir)) returncode = stdout.channel.recv_exit_status() if returncode != 0: msg = tr('Remote directory does not exist') ok = False else: ftpdir_exists = True except Exception as e: msg = tr('Error while checking the remote directory') msg += ': ' + str(e) ok = False client.close() if not ok: return False, msg, ftpdir_exists return True, '', ftpdir_exists
class SSH_Connection(): def __init__(self, user, host, password, index, cmd=None): ''' Object to facilitate SSH Connections :param user: string for username to connect to via ssh :param host: string of host ip address to connect to via ssh :param password: string for password to connect with via ssh ''' self.user = user self.host = host self.password = password self.ssh = SSHClient() self.ssh.set_missing_host_key_policy(AutoAddPolicy()) self.connected = True # bool for if connection is successful self.index = index self.cmd = cmd try: print("trying connect ", self.host, self.user, self.password) self.ssh.connect(self.host, username=self.user, password=self.password) except Exception as e: sys.stderr.write("SSH connection error: {0}".format(e)) self.connected = False print("failed ", self.host, self.user, self.password) if self.connected: print("connected ", self.host) def run_command(self, command): ''' Method to run SSH command :param command: string of bash command to execute ''' try: ssh_stdin, ssh_stdout, ssh_stderr = self.ssh.exec_command( command, get_pty=True) # https://askubuntu.com/questions/837633/top-not-showing-output-over-ssh # https://stackoverflow.com/questions/2909481/paramiko-and-pseudo-tty-allocation for line in ssh_stdout: print(self.host, ':', line) except Exception as e: # sys.stderr.write("SSH connection error: {0}".format(e)) print(e) def __del__(self): ''' Object deconstructor ''' self.ssh.close()
def commands(request: HttpRequest) -> HttpResponse: command_to_run = '' output = '' error = '' if request.method == 'POST': form = CommandForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] command_to_run = form.cleaned_data['command_to_run'] ssh = SSHClient() host_keys = ssh.get_host_keys() entry = HostKeyEntry.from_line( 'ssh.ocf.berkeley.edu ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAqMkHVVoMl8md25iky7e2Xe3ARaC4H1PbIpv5Y+xT4KOT17gGvFSmfjGyW9P8ZTyqxq560iWdyELIn7efaGPbkUo9retcnT6WLmuh9nRIYwb6w7BGEEvlblBmH27Fkgt7JQ6+1sr5teuABfIMg22WTQAeDQe1jg0XsPu36OjbC7HjA3BXsiNBpxKDolYIXWzOD+r9FxZLP0lawh8dl//O5FW4ha1IbHklq2i9Mgl79wAH3jxf66kQJTvLmalKnQ0Dbp2+vYGGhIjVFXlGSzKsHAVhuVD6TBXZbxWOYoXanS7CC43MrEtBYYnc6zMn/k/rH0V+WeRhuzTnr/OZGJbBBw==', # noqa ) host_keys.add( 'ssh.ocf.berkeley.edu', 'ssh-rsa', entry.key, ) try: ssh.connect( 'ssh.ocf.berkeley.edu', username=username, password=password, ) except AuthenticationException: error = 'Authentication failed. Did you type the wrong username or password?' if not error: _, ssh_stdout, ssh_stderr = ssh.exec_command(command_to_run, get_pty=True) output = ssh_stdout.read().decode() error = ssh_stderr.read().decode() else: form = CommandForm() return render( request, 'account/commands/index.html', { 'title': 'Account commands', 'form': form, 'command': command_to_run, 'output': output, 'error': error, }, )
def run_ssh_commands(ssh: paramiko.SSHClient, commands_list: list) -> list: """ :param ssh: ssh client :param commands_list: all commands need to run on remote host. :return: """ output = [] for command in commands_list: stdin, stdout, stderr = ssh.exec_command(command) out_info = stdout.readlines() for info_perline in out_info: output.append(info_perline) return output
def executeSSHcommandNonBlocking(self, command, continousAttempt=True, max_tries=10): tries = 0 while True: try: ssh = SSHClient() ssh.set_missing_host_key_policy(client.AutoAddPolicy()) ssh.connect(self.targetHostname, username=self.targetSSHusername, password=self.targetSSHpassword) ssh.exec_command(command) ssh.close() return except: if continousAttempt and tries < max_tries: tries = tries + 1 continue else: raise ("Exception: Unable to execute command " + str(command))
def main(): sshClient = SSHClient() sshClient.load_system_host_keys() global args for rpi in range(1,9): print(f'Connecting to Worker{rpi}') sshClient.connect(f'worker{rpi}', username='******', password='******') print('Executing: ' + args.command) _, stdout, _ = sshClient.exec_command(args.command) for line in stdout: print(f'Worker{rpi}: ' + line.strip('\n')) print("") if args.master or args.all: print(f'Connecting to Master') sshClient.connect(f'master', username='******', password='******') print('Executing: ' + args.command) _, stdout, _ = sshClient.exec_command(args.command) for line in stdout: print(f'Master: ' + line.strip('\n')) print("") if args.debian or args.all: print(f'Connecting to Debian') sshClient.connect(f'debian', username='******', password='******') print('Executing: ' + args.command) _, stdout, _ = sshClient.exec_command(args.command) for line in stdout: print(f'Debian: ' + line.strip('\n')) sshClient.close()
class SSH: def __init__(self, host, username, passwd): self.ssh = SSHClient() self.ssh.load_system_host_keys() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(hostname=host, username=username, password=passwd) def exec_cmd(self, host, cmd): stdin, stdout, stderr = self.ssh.exec_command(cmd) if stderr.channel.recv_exit_status() != 0: print(stderr.read()) else: return stdout.read().decode("utf-8")
def pushChanges(ipush_dict,mpush_dict,mgmt_ip): #uname=raw_input('Enter username for ' + mgmt_ip + ': ') #pw=raw_input('Enter password for above user : '******'root' pw='linux@123' ssh=SSHClient() ssh.load_system_host_keys() ssh.connect(mgmt_ip,username=uname,password=pw) for key,val in ipush_dict.items(): command='ip addr del '+val[0]+' dev '+key+'\nip addr add '+val[1]+' dev '+key print('Command executed : ' +command) si,so,se=ssh.exec_command(command) if se: print(se.readlines()) for key,val in mpush_dict.items(): print(mgmt_ip,key,val) command='sudo ifconfig '+key+' down\nsudo ifconfig '+key+' hw ether '+val+'\nsudo ifconfig '+key+' up' print('Command executed : '+command) si,so,se=ssh.exec_command(command) if se: print(se.readlines())
def start_app(key_filename, user_name, hostname): client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect( hostname=hostname, username=user_name, key_filename=key_filename, ) stdin, stdout, stderr = client.exec_command('./start.sh') stdin.flush() data = stdout.read().splitlines() for line in data: print line
class SSH: def __init__(self): self.ssh = SSHClient() self.ssh.load_system_host_keys() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(hostname='ip_address', username='******', pkey=k) def exec_cmd(self, cmd): stdin, stdout, stderr = self.ssh.exec_command(cmd) if stderr.channel.recv_exit_status() != 0: print stderr.read() else: print stdout.read()
class SSH: def __init__(self, **kwargs): self.client = SSHClient() self.client.set_missing_host_key_policy(AutoAddPolicy()) self.kwargs = kwargs def __enter__(self): kw = self.kwargs try: self.client.connect( hostname=kw.get('hostname'), port=int(kw.get('port', 22)), username=kw.get('username'), password=kw.get('password'), ) except AuthenticationException: print("Authentication failed, please verify your credentials") except SSHException as sshException: print(f"Could not establish SSH connection {sshException}") return self def __exit__(self, exc_type, exc_val, exc_tb): self.client.close() def exec_cmd(self, cmd): stdin, stdout, stderr = self.client.exec_command(cmd) data = stdout.read() data = data.decode() return data def exec_root(self, cmd): stdin, stdout, stderr = self.client.exec_command(f"sudo -S {cmd}") time.sleep(0.5) stdin.write("centos\n") stdin.flush() return stdout.read().decode()
class SSH: def __init__(self): self.ssh = SSHClient() self.ssh.load_system_host_keys() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(hostname=server ,port=port ,username=username,password=password) def exec_cmd(self,cmd): stdin,stdout,stderr = self.ssh.exec_command(cmd) if stderr.channel.recv_exit_status() != 0: print stderr.read() else: print "The password for next level is -> "+stdout.read()
def revoke_one_server(self, server, userhost, key_rsa, userName, usermail, port): """ Delete a heimdall replication. """ client = SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect('%s' % server, port=port, username=userhost) # ## Insert permission into server authorized_keys ssh file sshconfig_file = "~/.ssh/authorized_keys" rsa_search = str(key_rsa).replace('\r\n', '').replace('\r', '').replace('\n', '') stdin, stdout, stderr = client.exec_command("grep -v '%s' %s > %s.tmp" % (rsa_search, sshconfig_file, sshconfig_file)) stdin, stdout, stderr = client.exec_command("cat %s > %s.bak" % (sshconfig_file, sshconfig_file)) stdin, stdout, stderr = client.exec_command("chmod 0600 %s.tmp" % (sshconfig_file)) #stdin, stdout, stderr = client.exec_command("rm %s" % (sshconfig_file)) stdin, stdout, stderr = client.exec_command("mv %s.tmp %s" % (sshconfig_file, sshconfig_file)) stdin, stdout, stderr = client.exec_command("rm %s.bak" % (sshconfig_file)) logger.info("Access revoked") client.close() self.notify(server, userName, userhost, True, usermail)
def resultado(request): #Conexao com o Mikrotik # host = ("192.168.155.13") host = ("192.168.10.2") user = ("admin") password = (" ") sshCli = SSHClient() sshCli.set_missing_host_key_policy(AutoAddPolicy()) sshCli.connect(str(host), port=22, username=str(user), password=str(password)) #Pega os dados do Formulario if request.method == 'POST': form = FormMK(request.POST) if form.is_valid(): cidr = form.cleaned_data.get('cidr') if form.cleaned_data.get('opcao') == '1': stdin, stdout, stderr = sshCli.exec_command( 'ip route print detail where dst-address in ' + cidr) line = stdout.readlines() return render_to_response('saida.html', {'line': line}) elif form.cleaned_data.get('opcao') == '2': stdin, stdout, stderr = sshCli.exec_command('ping count=5 ' + cidr) line = stdout.readlines() return render_to_response('saida.html', {'line': line}) elif form.cleaned_data.get('opcao') == '3': stdin, stdout, stderr = sshCli.exec_command( 'tool traceroute ' + cidr) line = stdout.readlines() return render_to_response('saida.html', {'line': line}) elif form.cleaned_data.get('opcao') == '4': stdin, stdout, stderr = sshCli.exec_command( 'ipv6 route print detail where dst-address in ' + cidr) line = stdout.readlines() return render_to_response('saida.html', {'line': line}) elif form.cleaned_data.get('opcao') == '5': stdin, stdout, stderr = sshCli.exec_command('ping count=5 ' + cidr) line = stdout.readlines() return render_to_response('saida.html', {'line': line}) elif form.cleaned_data.get('opcao') == '6': stdin, stdout, stderr = sshCli.exec_command( 'tool traceroute ' + cidr) line = stdout.readlines() return render_to_response('saida.html', {'line': line}) else: form = FormMK() return render_to_response('index.html', {'form': form}, context_instance=RequestContext(request)) time.sleep(1) sshCli.close()
def oxe_update_ccca_cfg_dev_all_in_one(host, port, password, api_server): """Summary Args: host (TYPE): Description port (TYPE): Description password (TYPE): Description api_server (TYPE): Description """ # update ccca.cfg for all-in-one connection client = SSHClient() # use the paramiko SSHClient client.set_missing_host_key_policy( AutoAddPolicy()) # automatically add SSH key try: client.connect(host, port, username='******', password=password) except AuthenticationException: print('*** Failed to connect to {}:{}'.format(host, port)) command = "cat >> /usr3/mao/ccca.cfg << EOF\nRAINBOW_HOST={}\nEOF\n".format( api_server) # print(command) client.exec_command(command) client.close()
def sshwin(ip, username='', password='', p=22, timeout=5): try: s = SSHClient() s.set_missing_host_key_policy(AutoAddPolicy()) s.connect(ip, p, username=username, password=password, timeout=timeout) stdin, stdout, stderr = s.exec_command("echo alawashere", timeout=timeout) r = stdout.read() if "alawashere" in r: return True except Exception as e: pass return False
class SSH: def __init__(self): self.ssh = SSHClient() self.ssh.load_system_host_keys() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(hostname=IP, username=USERNAME, password=PASSWORD) def exec_cmd(self, comando): stdin, stdout, stderr = self.ssh.exec_command(comando) if stderr.channel.recv_exit_status() != 0: print(stderr.read()) else: print(stdout.read())
def garbage(func_get_host, properties): try: client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.load_system_host_keys() dict_hosts = func_get_host(properties['list_hosts']) for host, destiny in dict_hosts.items(): file_name = datetime.today() - \ timedelta(days=int(properties['expurgo'])) destiny_file_name = path.join(destiny, str( file_name.strftime('%d-%m-%Y') + '+.zip')) command_list = [ f'find {properties["origem"]} -type f \\( -iname {" -o -iname ".join(properties["file_type"].split())} \\) 2>/dev/null -exec zip -m {destiny_file_name} {{}} +', f'find {destiny} -type f -iname "*+.zip" -mtime +{properties["expurgo"]} 2>/dev/null -exec rm -f {{}} +"'] try: logging.info(str(f'Estabelecendo conexão com {host.upper()}')) client.connect( host, properties['port'], properties['username'], getpass()) except IOError as e: logging.error(str(f'Erro: IOError {host.upper()}. {e}')) continue except AuthenticationException as e: logging.error(f'Erro de autenticação {host.upper()}. {e}') continue except Exception as e: logging.error(f'Error inesperado. {e}') continue for sublist in command_list: try: stdin, stdout, stderr = client.exec_command( sublist, timeout=2.0) if stdout: for line in stdout: logging.info( f"Arquivo {line.split('/')[-1].strip()} >> {destiny}") if stdin or stderr: logging.warning("Não foi possível realizar a operação") except socket.timeout as e: logging.error(f'Erro ao executar comando. {e}') continue except Exception as e: logging.error(f'Erro inesperado. {e}') continue client.close() finally: if client: client.close()
def remote_backup(db_names: list, logger) -> None: try: # Connect to backup server ssh = SSHClient() ssh.load_system_host_keys() ssh.connect(REMOTE_HOST, username=REMOTE_USER) except Exception as e: logger.log( f"### ERROR ### while connecting to remote '{REMOTE_HOST}': {str(e)}" ) else: # Create remote backup folder try: ssh.exec_command(f"mkdir -p {TODAY_REMOTE_PATH}") ssh.close logger.log( f"Remote backup folder {TODAY_REMOTE_PATH} created on '{REMOTE_HOST}'" ) except Exception as e: logger.log( f"### ERROR ### while creating remote backup folder '{TODAY_REMOTE_PATH}' on '{REMOTE_HOST}': {str(e)}" ) else: # Initiate distant file transfer. SCPClient takes a paramiko transport as its only argument scp = SCPClient(ssh.get_transport()) # Copy on remote for db in db_names: try: scp.put(f"{TODAY_LOCAL_PATH}/{db}.sql", f"{TODAY_REMOTE_PATH}/{db}.sql") logger.log( f"Backup file '{db}.sql' has been copied on '{REMOTE_HOST}'" ) except Exception as e: logger.log( f"### ERROR ### while copying '{db}.sql' on '{REMOTE_HOST}': {str(e)}" ) scp.close()
def init(ssh: SSHClient, sftp: SFTPClient): # create working dir ssh.exec_command( f"if [ ! -d \"/home/{username}/workplace\" ]; then\nmkdir -p /home/{username}/workplace\necho {password} | sudo mount /mnt/sda1 /home/{username}/workplace\nfi" ) ssh.exec_command( f"echo {password} | sudo chown -R {username} /home/{username}/workplace" ) ssh.exec_command(f"cd /home/{username}/workplace") ssh.exec_command(f"rm -r {remote_working_dir}") ssh.exec_command(f"mkdir -p {remote_working_dir}") # upload code def upload_dir(local, remote): for kw in file_exclusion: if kw in local: return print(f"uploading {local} to {remote}") sftp.mkdir(str(Path(remote).joinpath(local))) for i in Path(local).rglob("*"): if i.is_dir(): upload_dir(str(i), remote) else: upload_file(str(i), str(Path(remote).joinpath(i))) def upload_file(local: str, remote: str): for kw in file_exclusion: if kw in local: return print(f"uploading {local} to {remote}") sftp.put(local, remote) for i in files_to_deploy: path = Path(i) if path.is_dir(): upload_dir(i, str(Path(remote_working_dir))) else: upload_file(i, str(Path(remote_working_dir).joinpath(i)))
class Sender: def __init__(self, config): self.zips_folder = config['GENERAL']['zips_folder'] self.relay_pcaps_folder = Path(config['RELAY_SERVER']['pcaps_folder']) self.ssh = SSHClient() self.ssh.set_missing_host_key_policy(AutoAddPolicy()) self.ssh.connect(config['RELAY_SERVER']['host'], username=config['RELAY_SERVER']['username'], password=config['RELAY_SERVER']['password']) self.scp = SCPClient(self.ssh.get_transport()) self.delete_completed = bool(config['GENERAL']['delete_completed']) def send(self, file_to_send: Path): temp_file_to_send = file_to_send.with_suffix('.tempzip') rename(file_to_send, temp_file_to_send) self.scp.put(str(temp_file_to_send), str(self.relay_pcaps_folder.as_posix())) print('Sent ' + temp_file_to_send.name) file_server_path = self.relay_pcaps_folder / temp_file_to_send.name if self.delete_completed: remove(temp_file_to_send) self.ssh.exec_command('mv {} {}'.format( file_server_path.as_posix(), file_server_path.with_suffix('.zip').as_posix())) print('Renamed') def zip(self, file_to_zip: Path): zip_path = file_to_zip.parents[ 1] / self.zips_folder / file_to_zip.with_suffix('.zip').name with ZipFile(str(zip_path), "w", compression=ZIP_BZIP2) as compressed: compressed.write(file_to_zip, file_to_zip.name) if self.delete_completed: remove(file_to_zip) print('Zipped ' + zip_path.name) return zip_path
def execute(client: SSHClient, command: str, *, is_silent=True): with monit.section(f'Exec: {command}', is_silent=is_silent): stdin, stdout, stderr = client.exec_command(command) out = stdout.read().decode('utf-8').strip() err = stderr.read().decode('utf-8').strip() exit_code = stdout.channel.recv_exit_status() if err != '': logger.log("Errors:", Text.warning) print(err) if exit_code != 0: monit.fail() return exit_code, out
def sshPipe(selfm, command): "function creating and closing ssh pipe" client = SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect(var.SSHADDR, username=var.SSHUSER, port=var.SSHPORT) stdin, stdout, stderr = client.exec_command(command) str = "" for line in stdout: str += line client.close() return str
class SSH: def __init__(self): self.ssh = SSHClient() self.ssh.load_system_host_keys() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(hostname='104.41.42.124',username='******',password='******') def exec_cmd(self,cmd): stdin,stdout,stderr = self.ssh.exec_command(cmd) if stderr.channel.recv_exit_status() != 0: print (stderr.read()) else: print (stdout.read())
def execute_remote_cmd(ssh: SSHClient, command: str) -> Tuple[Sequence[str], Sequence[str]]: # Send the command (non-blocking) stdin, stdout, stderr = ssh.exec_command(command, get_pty=True) # Wait for the command to terminate while not stdout.channel.exit_status_ready() and not stdout.channel.recv_ready(): time.sleep(0.001) exit_status = stdout.channel.recv_exit_status() # Blocking call if exit_status != 0: raise RuntimeError("Unable to capture remote screen: {}".format(exit_status)) stdoutstring = stdout.readlines() stderrstring = stderr.readlines() return stdoutstring, stderrstring
def execute_script(script_loc, script_name, host, port=22, username=getpass.getuser(), password=None, change_user='******'): client = SSHClient() client.load_system_host_keys() client.connect(host, username=username, password=password) stdin, stdout, stderr = client.exec_command('sudo -u %s' % change_user + ';cd %s' % script_loc + ';' + './%s' % script_name) return stdout, stderr
def change_password(now, ssh: paramiko.SSHClient, target_password: str): print('开始修改密码...') stdin, stdout, stderr = ssh.exec_command('passwd') time.sleep(1) stdin.write(target_password + "\n") time.sleep(1) stdin.write(target_password + "\n") stdin.flush() res, err = stdout.read(), stderr.read() result = res if res else err if 'password updated successfully' in result.decode(): notice(now + '\nDD 已完成\n密码修改为' + target_password) else: notice(now + '\nDD 已完成\n密码修改失败')
def remotestartup(self): ssh = SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(AutoAddPolicy) ssh.connect( self.cfg["connection"]["bbbip"], username=self.cfg["connection"]["bbbuser"], password=self.cfg["connection"]["bbbpw"]) #create the destination folder if it does not exist log.debug("updating bbb program", extra = log.HST) src = op.abspath(self.cfg["connection"]["bbbsrc"]) dst = self.cfg["connection"]["bbbdst"] (sshin1, sshout1, ssherr1) = ssh.exec_command(f"mkdir -p {dst}") #copy the cfg file and the bbb code with SCPClient(ssh.get_transport()) as scp: scp.put(self.cfg.filename, remote_path=dst) scp.put(src, recursive=True, remote_path=dst) (sshin2, sshout2, ssherr2) = ssh.exec_command(f"python3 {dst}/bbb/__main__.py",get_pty=True) log.debug("started bbb program", extra = log.HST) self.sshout = sshout2 self.ssh = ssh
def Connection_Routs(): mip = '172.31.1.194' ml = 'admin' mp = 'Myxa194' #ssh # Объявим переменную подключения глобальной для того чтобы обратится извне ssh = SSHClient() # Создаем клиент подключения ssh.set_missing_host_key_policy( AutoAddPolicy()) # Создаем стек ключей подлкючения для доступа ssh.connect(mip, port=22, username=ml, password=mp) # Проводим подключение к микротику command = "/ip route print" ssh_command = ssh.exec_command(command)[1].read() ssh_command = ssh_command.decode("utf-8") print(ssh_command)