def onButtonCopyLogs(self, event): self.editoutput.AppendText("# Connecting...\n") wx.Yield() # subprocess.call(["scp -P2222 [email protected]:/home/essien/testbed/parallel-wsn/logs/* /home/mark/Code/2011-Essien-Mark/Src/ukleos/projects/security/microeval/logs/",""],shell=True) # os.system("scp -P2222 [email protected]:/home/essien/testbed/parallel-wsn/logs/* /home/mark/Code/2011-Essien-Mark/Src/ukleos/projects/security/microeval/logs/") # return s = ssh.Connection(DEPLOY_SERVER, port=DEPLOY_SERVER_PORT, username=self.edituser.GetValue(), password=self.editpw.GetValue()) self.editoutput.AppendText("# Result=" + str(s) + "\n") wx.Yield() self.editoutput.AppendText("# Copying log files\n") f = open(LOCAL_ADDRESS_LIST) for line in f.readlines(): wx.Yield() line = line.strip('\n') log_name = LOG_PREFIX + line + ".log" self.editoutput.AppendText("Copying log " + log_name + "\n") try: s.get(REMOTE_LOG_DIR + log_name, "./logs/" + log_name) self.editoutput.AppendText("...copied\n") except: self.editoutput.AppendText("...not found\n") self.editoutput.AppendText("# Files copied.\n") wx.Yield() self.editoutput.AppendText("# Closing Connection\n\n") s.close()
def onButtonFlashNodes(self, event): self.editoutput.AppendText("# Connecting...\n") s = ssh.Connection(DEPLOY_SERVER, port=DEPLOY_SERVER_PORT, username=self.edituser.GetValue(), password=self.editpw.GetValue()) self.editoutput.AppendText("# Result=" + str(s) + "\n") self.editoutput.AppendText("# Copying hex file...\n") wx.Yield() try: # Obviously you should change this path. Be sure to make hex folder (within testbed) result = s.put(LOCAL_HEX_FILE, REMOTE_HEX_FILE) self.editoutput.AppendText(str(result)) except: self.editoutput.AppendText("# Local file not found!!!\n") self.editoutput.AppendText("# Copy complete\n") self.editoutput.AppendText( "# Flashing nodes now (needs about 5 minutes)\n") wx.Yield() results = s.execute( "parallel-ssh -h hosts.txt -t 180 'lpc2k_pgm /dev/ttyUSB0 " + REMOTE_HEX_FILE_NODE + "'") for result in results: self.editoutput.AppendText(result) self.editoutput.AppendText("# Closing Connection\n\n") s.close()
def onButtonSetAddresses(self, event): self.editoutput.AppendText("# Connecting...\n") s = ssh.Connection(DEPLOY_SERVER, port=DEPLOY_SERVER_PORT, username=self.edituser.GetValue(), password=self.editpw.GetValue()) self.editoutput.AppendText("# Result=" + str(s) + "\n") wx.Yield() self.editoutput.AppendText("# Setting address on nodes\n") item = 1 f = open(LOCAL_ADDRESS_LIST) for line in f.readlines(): line = line.strip('\n') self.editoutput.AppendText("Setting address on " + line) results = s.execute(PARALLEL_WSN_PATH + 'parallel_wsn.py -c ' + PARALLEL_WSN_PATH + 'parallel-wsn.config -H ' + line + ' "set addr 10.' + str(item) + '"') for result in results: self.editoutput.AppendText(result) print result self.editoutput.AppendText("# Set address of " + line + " to 10." + str(item) + "\n") item = item + 1 wx.Yield() self.editoutput.AppendText("# Closing Connection\n\n") s.close()
def ssh_connect(self): try: self.connection = ssh.Connection(self.host, username=self.username, password=self.password) except: print "ホスト名,ユーザ名,パスワードいずれかが正しくないので接続できませんでした" sys.exit()
def startssh(): try: server = ssh.Connection(host='54.200.62.243', username='******', private_key='tubuntu.pem') except: print('Error Connecting to AWS Server') exit() return server
def main(outfile=None): # get switch information switch = raw_input("Switch to connect to: ") username = raw_input("Username [%s]: " % getpass.getuser()) if username == None: username = getpass.getuser() password = getpass.getpass("Password: "******"There was an error connecting to %s." % switch sys.exit(2) portList = [] # grab our list and get out output = s.execute( 'show interfaces terse | grep down | except \.0 | grep ge-') for port in output: port = port.strip() if port == '': continue p = port.split()[0] portList.append({'port': p, 'lastflapped': getLastFlapped(p, s)}) s.close() # process and write the output to a variable display = "Ports currently down on switch %s: \n" % switch for p in portList: display = display + " %s\t: %s\n" % (p['port'], p['lastflapped']) # Check to see if we are to write the output to a file # or the screen if outfile: try: f = open(outfile, 'w') except: print "Error... couldn't write to %s" % outfile sys.exit(3) f.write(display) f.close() else: print display
def upload_file(request): """ Runs the executable and records time elapsed """ if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) form.fields['blade'].initial = [0] if form.is_valid(): handle_uploaded_file(request.FILES["file"]) file_name = request.FILES["file"].name # Select daq based on blade blade = request.POST['blade'] if blade == 0 or blade == 1 or blade == 4: daq = 0 else: daq = 2 # Run the executable parameters = request.POST['parameters'] start = time.time() s = ssh.Connection('ac' + blade, username=account_info.username, password=account_info.password) results = s.execute('time ~/PowerViz_Executables/executable ' + parameters) end = time.time() s.close() elapsed = str(end - start) + " s" cache.set('start_time', start, 7200) cache.set('end_time', end, 7200) print "Just set start_time to: " + str(cache.get('start_time')) print "Just set end_time to: " + str(cache.get('end_time')) # Record results to the dictionary c = {"results":results[0], "time": elapsed} return render_to_response("upload_success.html", {'c': c}) # Create the form c = RequestContext(request) # Create the form for uploading the file form = UploadFileForm() c["form"] = form return render_to_response("upload.html", c)
def onButtonTest(self, event): self.editoutput.AppendText("# Connecting...\n") s = ssh.Connection(DEPLOY_SERVER, port=DEPLOY_SERVER_PORT, username=self.edituser.GetValue(), password=self.editpw.GetValue()) self.editoutput.AppendText("# Result=" + str(s) + "\n") wx.Yield() # s.put('hello.txt') # s.get('goodbye.txt') self.editoutput.AppendText("# > ls\n") results = s.execute('ls') for result in results: if result: self.editoutput.AppendText(result) self.editoutput.AppendText("# Closing Connection\n\n") s.close()
def main(outfile=None): # get router information router = raw_input("Router to connect to: ") username = raw_input("Username [%s]: " % getpass.getuser()) if username == None: username = getpass.getuser() password = getpass.getpass("Password: "******"There was an error connecting to %s." % router sys.exit(2) # grab our list and get out contents = s.execute( 'show security flow session interface reth5.0 node primary') s.close() # process and write the output to a variable ipaddrs = calculate_IP_nats(contents) output = str() for i, d in ipaddrs.iteritems(): output += i + " - " + str(len(d)) + " connections" + "\n" if len(d) > 60: for c in d: output += "\t [" + c[0] + "] --> " + c[1] + " [" + c[ 2] + "]" + "\n" # Check to see if we are to write the output to a file # or the screen if outfile: try: f = open(outfile, 'w') except: print "Error... couldn't write to %s" % outfile sys.exit(3) f.write(output) f.close() else: print output
def onButtonStartParallelWSN(self, event): self.editoutput.AppendText("# Connecting...\n") s = ssh.Connection(DEPLOY_SERVER, port=DEPLOY_SERVER_PORT, username=self.edituser.GetValue(), password=self.editpw.GetValue()) self.editoutput.AppendText("# Result=" + str(s) + "\n") wx.Yield() self.editoutput.AppendText("# Starting WSN-Daemon on nodes\n") results = s.execute("parallel-ssh -h hosts.txt -t 180 '" + PARALLEL_WSN_PATH_NODE + "parallel_wsn_daemon.py -c " + PARALLEL_WSN_PATH_NODE + "parallel-wsn-daemon.config restart'") for result in results: self.editoutput.AppendText(result) wx.Yield() self.editoutput.AppendText("# Closing Connection\n\n") s.close()
def deploy_to_server(): """ Copies the files from the local machine to the server. Files transfered from _files_to_transfer. _files_to_transfer - (source_file, server_destination_path) TODO: Implement... """ usr = raw_input('Enter username: '******'Enter server password: '******'if [ ! -d "%s" ]; then mkdir -p "%s"; fi' % (server_install_path, server_install_path)) for (from_file, to_file) in _files_to_transfer: output_line('Copying %s' % os.path.basename(from_file)) # print from_file # print to_file s.put(from_file, to_file) s.execute('cd ' + server_sql_path + '; php run_api_menu_script.php') s.close()
if result[i] > result[maxi]: maxi=i opt[maxi].config(fg="green") def sockit(): sid = getsid() r2 = requests.get(main_url+"&sid="+sid, headers = headers, cookies = cookies) rdata2 = r2.text connectsocket(sid) root = Tk() server = ssh.Connection(host='54.200.62.243', username='******', private_key='tubuntu.pem') headFrame = Frame(root) headFrame.pack() thelbl = Label(headFrame, text="QuizBot- Client Version") conxn = Label(headFrame, text="(Connected)", fg="green") thelbl.pack(side = LEFT) conxn.pack(side = LEFT) socklbl = Label(headFrame, text = "Not connected to Socket..") socklbl.pack() middleFrame = Frame(root) middleFrame.pack()
def main(): global hostname, username, password, keyfile local_folder = None remote_folder = None use_ftp = False opts, args = getopt.getopt(sys.argv[1:], 'h:u:p:', ['key=', 'ftp']) for name, value in opts: if name == '-h': hostname = value elif name == '-u': username = value elif name == '-p' and value.strip() != '': password = value elif name == '--key' and value.strip() != '': keyfile = value elif name == '--ftp': use_ftp = True if len(args) < 2 or hostname is None: usage() if username is None: username = raw_input("Enter username: "******"Enter password: "******"%s" for changes...' % local_folder) while True: try: update_folder(con, local_folder, remote_folder) except FileNotFoundError: print("Exception caught") #print('.') time.sleep(1) con.close()
def EnumClients2(ip, port, op): global daemon_path, flags global team, ports, exit_value global ctf_config DebugLog("EnumClients2 : %s %s %s" % (ip, port, op)) #SSH to the target try: myssh = ssh.Connection(ip, ctf_config["SSH_UNAME"][1], ctf_config["SSH_PRIVKEY"][1], port=int(ctf_config["SSH_PORT"][1])) except: Log("!!! %s(%s:%s) Unable to establish an SSH connection" % (team[ip][0], ip, ctf_config["SSH_PORT"][1])) exit_value = CTF_FAIL return #Log nothing myssh.execute("HISTFILE=/dev/null") #The reason port is enumerated here is because we only need 1 ssh connection and not to #establish a new connection for every port which slows shit down a ton. for p in ports: if port == 0 or p == port: #Check if daemon_path has this port if p not in daemon_path: Log("Port %s does not exist in daemon_info for %s" % (p, ip)) exit_value = CTF_INTERR continue #Check if we have a valid flag entry for this IP and port if ip not in flags or p not in flags[ip]: Log("Unable to find flag data for %s:%s" % (ip, p)) exit_value = CTF_INTERR continue if op == CTF_GETFLAG or op == CTF_CHECKFLAG: #Check if flag file is legit user_hash = getFileHash(myssh, daemon_path[p][0] + daemon_path[p][2]) if user_hash == CTF_INTERR: EnumCleanup(myssh) continue if op == CTF_GETFLAG: Log("%s(%s:%s) FlagHash : %s" % (team[ip][0], ip, p, user_hash)) exit_value = CTF_SUCCESS else: #Check flag #Check flag checks afew things #1. Check if the correct daemon is listening on the correct port # Do not accept daemon from a diff location #2. Check if daemon has not been tampered with #3. Daemon is correctly responding #4. Check if hash of flagfile is valid #1 Check correctness #Get daemon listening on specific port to extract pid cmd_exec = "sudo netstat -nlp | grep LISTEN | grep :%s" % ( p, ) DebugLog(cmd_exec) ret = myssh.execute(cmd_exec) if len(ret) == 0: Log("Daemon %s:%s not listening" % ( ip, p, )) EnumCleanup(myssh) exit_value = CTF_FAIL continue #Take the first entry found pid = ret[0].rsplit()[6].split("/")[0] DebugLog("Found PID : %s" % pid) #Resolve PID cmd_exec = "sudo ls -l /proc/%s/exe" % (pid, ) DebugLog(cmd_exec) ret = myssh.execute(cmd_exec) if len(ret) == 0: Log("Unable to resolve PID for daemon %s:%s" % ( ip, p, )) EnumCleanup(myssh) exit_value = CTF_FAIL continue #Compare running path to what we have ret = ret[0].split(" -> ") if len(ret) != 2: Log("!!!Wrong daemon running on %s:%s!!!" % ( ip, p, )) EnumCleanup(myssh) exit_value = CTF_FAIL continue ret = ret[1].strip("\n") if ret != daemon_path[p][0] + daemon_path[p][1]: Log("!!!Wrong daemon running on %s:%s (%s)!!!" % ( ip, p, ret, )) EnumCleanup(myssh) exit_value = CTF_FAIL continue #2 Check if FILEHASH is correct file_hash = getFileHash( myssh, daemon_path[p][0] + daemon_path[p][1]) if file_hash == CTF_INTERR: Log("Unable to hash daemon file on %s:%s (%s)" % (ip, p, daemon_path[p][0] + daemon_path[p][1])) EnumCleanup(myssh) exit_value = CTF_FAIL continue if file_hash != checksums[p][0]: Log("!!!Daemon hash mismatched (Returned-%s/Expected-%s)!!!" % (file_hash, checksums[p][0])) EnumCleanup(myssh) exit_value = CTF_FAIL continue useDefault = False #3 Daemon Network Validation #Check if we can get a valid response from the port, this is to prevent firewalling try: mod = __import__(daemon_path[p][3]) #Check if function validate_daemon exists if not hasattr(mod, "validate_daemon"): Log("!!!Unable to find function validate_daemon in %s, reverting to default callback" % (daemon_path[p][3], )) useDefault = True except: Log("!!!Unable to import %s, reverting to default callback!!!" % (daemon_path[p][3], )) useDefault = True if useDefault == True: DebugLog("Calling defaultConnCheck(%s,%s)" % ( ip, p, )) ret = defaultConnCheck(ip, p) else: DebugLog("Calling mod.validate_daemon(%s,%s,%s)" % ( ip, p, flags[ip][p][0], )) ret = mod.validate_daemon(ip, p, flags[ip][p][0]) if ret != CTF_SUCCESS: Log("!!!Daemon network validation FAILED (%s:%s)!!!" % ( ip, p, )) EnumCleanup(myssh) if not useDefault == True: del mod exit_value = CTF_FAIL continue if not useDefault == True: del mod #4 #Now check if the flag has been pwned real_hash = flags[ip][p][1] if real_hash != user_hash: Log("!!! %s(%s:%s) PWNED Client FlagHash (Returned-%s/Expected-%s)!!!" % (team[ip][0], ip, p, user_hash, real_hash)) EnumCleanup(myssh) exit_value = CTF_FAIL continue Log("!!!Flag Matches for %s:%s!!!" % (ip, p)) #Remove leftovers EnumCleanup(myssh) exit_value = CTF_SUCCESS elif op == CTF_GETHASHFILE or op == CTF_CHECKHASHFILE: file_hash = getFileHash(myssh, daemon_path[p][0] + daemon_path[p][1]) if file_hash == CTF_INTERR: EnumCleanup(myssh) continue if op == CTF_GETHASHFILE: Log("%s(%s:%s) File Hash : %s" % (team[ip][0], ip, p, file_hash)) exit_value = CTF_SUCCESS else: #check againts what we have in file if file_hash == checksums[p][0]: Log("!!! %s(%s:%s) File Hash Matched (Returned-%s/Expected-%s)!!!" % (team[ip][0], ip, p, file_hash, checksums[p][0])) exit_value = CTF_SUCCESS else: Log("!!! %s(%s:%s) Invalid File Hash (Returned-%s/Expected-%s)!!!" % (team[ip][0], ip, p, file_hash, checksums[p][0])) exit_value = CTF_FAIL EnumCleanup(myssh) myssh.close()
from datetime import date from time import gmtime, strftime from datetime import datetime import Class_PreProcess import ssh server = ssh.Connection(host='172.16.0.39', username='******', password='******') result = server.execute('ping 172.16.0.17') ''' def fslice(param1): s = param1.split(' ')[1] exec(s + f'{()}') def fhour(): now = date.today() t = strftime("%a, %d %b %Y %H:%M:%S -0003", gmtime()) print(t) def helloworld(): print('F*****g hello word.') s = 'function hora' print(s.split(' ')[1]) response = 'function helloworld' response2 = response.split(' ')[0] print(response2) if response2 == 'function':
import ssh for environment in environments: # Determining variables for current environment: curr = {} for option_name in [ 'name', 'host', 'username', 'private_key', 'command', 'indent' ]: curr[option_name] = environment.get(option_name, defaults.get(option_name)) print '[Connecting to ' + bold(curr['name']) + ']' print server = ssh.Connection(host=curr['host'], username=curr['username'], private_key=curr['private_key']) result = server.execute(curr['command']) # Cleanup lines result = [line.strip(' \n\t') for line in result] # Display results if result.count('Already up-to-date.') > 0 and len(result) == 1: print curr['indent'] + success('(up-to-date)') print else: for line in result: print curr['indent'] + warning(line) print
def handle_ssh_connection(self, client): self._handle_connection( client, lambda client, connection_id: ssh.Connection(client, connection_id, self.publisher, self.keyfile) )
import ssh server = ssh.Connection(host='10.100.52.148', username='******', private_key='mayank') result = server.execute('ls') print(result)