def run_nginx_check(): global instance if running_check(): try: dns = instance.public_dns_name (status, output) = ssh.connect(dns, private_key_name, "sudo python3 check_webserver.py") if "command not found" in output: print("It doesn't look like you've installed python, please try that first.") elif "No such file" in output: print("It doesn't look like you've copied the file to the instance, please try that first.") else: print(output) if status > 0: choice = input("Would you like to start nginx? (y/n) ") if choice == "y": (stat, out) = ssh.connect(dns, private_key_name, "sudo service nginx start") if "unrecognized service" in out: print("It doesn't look like you've installed nginx, please try that first.") run_nginx_check() else: print("Nginx not started.") except Exception as e: error = str(e) print("Something went wrong. Please try again.") logger.status_log("run_nginx_check method failed. Error: " + error)
def copy_web_script(): global instance if running_check(): try: print("Copying script...") dns = instance.public_dns_name (status, output) = ssh.copy(dns, private_key_name, "check_webserver.py", "") if status > 0: logger.status_log("Can't connect using ssh. Error message: ") logger.status_log(output) print("Something isn't quite right. Please try again.") return else: (status, output) = ssh.connect(dns, private_key_name, "ls") print("Current directory: ") print(output) (status, output) = ssh.connect(dns, private_key_name, "chmod 700 check_webserver.py") except Exception as e: error = str(e) print("Something went wrong. Please try again.") logger.status_log("copy_web_script method failed. Error: " + error)
def view_error_log(): global instance if running_check(): try: dns = instance.public_dns_name ssh.connect(dns, private_key_name, "sudo chmod 777 /var/log/nginx") cmd = "nano /var/log/nginx/error.log" command = "ssh -t -o StrictHostKeyChecking=no -i " + private_key_name + ".pem ec2-user@" + dns + " " + cmd print(os.system(command)) except Exception as e: error = str(e) print("Something went wrong. Please try again.") logger.status_log("view_error_log method failed. Error: " + error)
def openSSHSession(self): #pass if self._sshSession is not None: return ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(self.IP, username='******', password=self.Password, port=self.Port) ssh.exec_command('s') ssh.exec_command('l') ssh.exec_command('visonic') transport = ssh.get_transport() channel = transport.open_session() # self._sshSession = ssh self._sshChannel = channel
def test_conn_execute(self): def on_connected(conn): conns.append(conn) return conn.execute("echo 'hello'") def on_executed(process): process.stdout.add_callback(data.append) return process.exited.next_event() def on_exited(_): self.assertTrue("hello" in "".join(bToStr(data)), msg="Expected to find 'hello' in output. Got: %s" % repr(bToStr(data))) return conns[0].close() data = [] conns =[] conn_defer = ssh.connect(test_credentials.ssh_hostname, test_credentials.ssh_user, private_key_files=[test_credentials.ssh_privatekey]) conn_defer.addCallback(on_connected) conn_defer.addCallback(on_executed) conn_defer.addCallback(on_exited) return conn_defer
def get_luns(self, sid, sg): command = '' print('List volumes for each SG') for each_sg in str(sg).split('\n'): command = 'export SYMCLI_CONNECT=VMAX' + sid + ';symdev -sid ' + sid + ' list -sg ' + each_sg luns = ssh.connect(self.ip, self.username, self.password, command).strip() print(luns)
def test_conn_execute_disconnect(self): def on_connected(conn): conns.append(conn) return conn.execute("sleep 100") def on_executed(process): conns[0].close() return process.exited.next_event() def on_success(_): self.fail("Expected failure due to non-zero exit code.") def on_fail(reason): self.assertTrue(reason.check(ConnectionLost), "reason is not of type ConnectionLost") conns =[] conn_defer = ssh.connect(test_credentials.ssh_hostname, test_credentials.ssh_user, private_key_files=[test_credentials.ssh_privatekey]) conn_defer.addCallback(on_connected) conn_defer.addCallback(on_executed) conn_defer.addCallbacks(on_success, on_fail) return conn_defer
def _main( listener, fw, ssh_cmd, remotename, python, latency_control, dnslistener, udp_server, udp_forward, seed_hosts, auto_nets, syslog, daemon, ): handlers = [] if helpers.verbose >= 1: helpers.logprefix = "c : " else: helpers.logprefix = "client: " debug1("connecting to server...\n") try: (serverproc, serversock) = ssh.connect( ssh_cmd, remotename, python, stderr=ssyslog._p and ssyslog._p.stdin, options=dict(latency_control=latency_control), ) except socket.error, e: if e.args[0] == errno.EPIPE: raise Fatal("failed to establish ssh session (1)") else: raise
def bring_back_node_in_rabbit_cluster(configuration: Configuration = None, secrets: Secrets = None): rmq_client = rmq_client_connect(configuration, secrets) client = ssh.connect(secrets) stdin, stdout, stderr = client.exec_command( 'sudo /usr/sbin/rabbitmqctl start_app') client.close() rmq_client = rmq_client_connect(configuration, secrets)
def linux(): if request.method == 'POST': f =request.files['file'] f.save(secure_filename(f.filename)) # Connect the linux with ssh ssh = paramiko.SSHClient() # Load or generate the host key ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Connect the server ssh.connect("58.206.100.172", port=2222, username="******", password="******") # stdin,stdout,stderr = ssh.exec_command('mkdir aliServer') with closing(scpclient.Write(ssh.get_transport(), remote_path="/home/keyyd/aliServer")) as scp: scp.send_file(f.filename, preserve_times=True) stdin, stdout, stderr = ssh.exec_command('python aliServer/main.py') return render_template('help.html', name=f.filename, data=stdout.read())
def get_sg(self, sid, account): # Get storage group name from target VMAX print('Connect to SYMCLI server') command = 'export SYMCLI_CONNECT=VMAX' + sid + '; symaccess -sid ' + sid + ' list view -v | grep ' + account + ' | grep \'Storage Group Name\' | awk \'{print $NF}\' | awk \'!seen[$1]++\'' sg = ssh.connect(self.ip, self.username, self.password, command).strip() for each in str(sg).split('\n'): print('\t' + each) return sg
def lambda_handler(event, context): # TODO implement logger.info(event) logger.info("After event") s3_client = boto3.client('s3') s3_client.download_file('thulasi-ram-dum', 'ec2andemr.pem', '/tmp/ec2.pem') ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) privkey = paramiko.RSAKey.from_private_key_file('/tmp/ec2.pem') #instance_id = "i-058481edd4788c01c" ssh.connect('ec2-18-221-144-29.us-east-2.compute.amazonaws.com', username='******', pkey=privkey) stdin, stdout, stderr = ssh.exec_command( 'echo "ssh to ec2 instance successful"') data = stdout.read().splitlines() for line in data: print(line) return {"statusCode": 200, "body": json.dumps('Hello from Lambda!')}
def node_failure_in_rabbit_cluster(configuration: Configuration = None, secrets: Secrets = None): rmq_client = rmq_client_connect(configuration, secrets) client = ssh.connect(secrets) stdin, stdout, stderr = client.exec_command( 'sudo /usr/sbin/rabbitmqctl stop_app') o, r = stdout.read().decode('utf-8'), stderr.read().decode('utf-8') client.close() logger.info(o) if r != "": logger.warn(r)
def test_connect_passwd(self): def on_connected(conn): d = conn.closed.next_event() conn.close() return d conn = ssh.connect(test_credentials.ssh_hostname, test_credentials.ssh_user, password = test_credentials.ssh_password) conn.addCallback(on_connected) return conn
def probe_app_can_connect_and_send_message_to_rabbit( configuration: Configuration = None, secrets: Secrets = None): if not secrets: raise ActivityFailed( "Please set the secrets entry to specify the SSH client settings") # Create ssh client client = ssh.connect(secrets) # Get RabbitMQ connection params from secrets rmq_api_rest_endpoint = os.getenv(secrets.get("rabbitmq_restendpoint")) rmq_username = os.getenv(secrets.get("rabbitmq_username")) rmq_password = os.getenv(secrets.get("rabbitmq_password")) rmq_vhost_url = os.getenv( secrets.get("rabbitmq_host")) + "/api/healthchecks/node" rabbit_creds = rmq_username + ":" + rmq_password wait_time = int(os.getenv('WAIT_TIME')) if wait_time > 0: logger.info("Waiting for " + str(wait_time) + " secs before connecting to rabbit") time.sleep(wait_time) rabbitmq_connect_curl = 'curl -s -u {rabbitmq_creds} {rabbitmq_host}'.format( rabbitmq_creds=rabbit_creds, rabbitmq_host=rmq_vhost_url) stdin, stdout, stderr = client.exec_command(rabbitmq_connect_curl) o, r = stdout.read().decode('utf-8'), stderr.read().decode('utf-8') client.close() logger.info(o) error = False if r != "": logger.warn(r) error = True rmq_client = rmq_client_connect(configuration, secrets) rmq_client.create_vhost("ce_vhost") rmq_client.create_exchange("ce_vhost", "ce_exc", "direct") rmq_client.create_queue("ce_vhost", "ce_que") rmq_client.create_binding("ce_vhost", "ce_exc", "ce_que", "ce.rtkey") if not rmq_client.publish('ce_vhost', 'ce_exc', 'ce.rtkey', 'chaos experiment message'): error = True rmq_client.delete_vhost("ce_vhost") return not error
def test_connect_key(self): def on_connected(conn): d = conn.closed.next_event() conn.close() return d conn = ssh.connect(test_credentials.ssh_hostname, test_credentials.ssh_user, private_key_files=[test_credentials.ssh_privatekey]) conn.addCallback(on_connected) return conn
def twisted_setup(self): def on_connected(conn): self.connection = conn return conn.open_sftp() def on_sftp_open(sftp): self.sftp = sftp conn_defer = ssh.connect(test_credentials.ssh_hostname, test_credentials.ssh_user, private_key_files=[test_credentials.ssh_privatekey]) conn_defer.addCallback(on_connected) conn_defer.addCallback(on_sftp_open) return conn_defer
def test_connect_key_string(self): def on_connected(conn): d = conn.closed.next_event() conn.close() return d keyfile = open(test_credentials.ssh_privatekey,'r') conn = ssh.connect(test_credentials.ssh_hostname, test_credentials.ssh_user, private_keys=[keyfile.read()]) conn.addCallback(on_connected) return conn
def test_connect_wrong_passwd(self): def on_connected(conn): return conn.close() def on_error(reason): if not reason.check(AuthenticationFailed): self.fail("Expected AuthenticationFailed") conn = ssh.connect(test_credentials.ssh_hostname, test_credentials.ssh_user, password = "******") conn.addCallbacks(on_connected, on_error) return conn
def install_python(): global instance if running_check(): try: dns = instance.public_dns_name (status, output) = ssh.connect(dns, private_key_name, "sudo yum -y install python34") if status == 0: print("Python installed successfully!") else: logger.status_log("Python not installed correctly.") try_again = input("Oops, something wen't wrong installing python. Try again? (y/n) ") if try_again == "y": install_python() except Exception as e: error = str(e) print("Something went wrong. Please try again.") logger.status_log("install_python method failed. Error: " + error)
def probe_running_rabbitmq_service(configuration: Configuration = None, secrets: Secrets = None): if not secrets: raise ActivityFailed( "Please set the secrets entry to specify the SSH client settings") client = ssh.connect(secrets) stdin, stdout, stderr = client.exec_command( 'sudo /usr/sbin/rabbitmqctl status | grep pid | grep -Eo \'[0-9]{1,5}\'' ) o, r = stdout.read().decode('utf-8'), stderr.read().decode('utf-8') client.close() if r != "": logger.warn(r) return False return True
def install_nginx(): global instance if running_check(): try: print("Installing nginx...") dns = instance.public_dns_name (status, output) = ssh.connect(dns, private_key_name, "sudo yum -y install nginx") if status > 0: print("Something went wrong. Check error log for information.") logger.status_log("Can't install nginx using SSH. Error message: ") logger.status_log(output) else: print("Nginx successfully installed on instance.") except Exception as e: error = str(e) print("Something went wrong. Please try again.") logger.status_log("install_nginx method failed. Error: " + error)
def _main(listener, fw, ssh_cmd, remotename, python, latency_control, dnslistener, seed_hosts, auto_nets, syslog, daemon): handlers = [] if helpers.verbose >= 1: helpers.logprefix = 'c : ' else: helpers.logprefix = 'client: ' debug1('connecting to server...\n') try: (serverproc, serversock) = ssh.connect(ssh_cmd, remotename, python, stderr=ssyslog._p and ssyslog._p.stdin, options=dict(latency_control=latency_control)) except socket.error, e: if e.args[0] == errno.EPIPE: raise Fatal("failed to establish ssh session (1)") else: raise
def test_conn_sftp(self): def on_connected(conn): conns.append(conn) return conn.open_sftp() def on_sftp_open(sftp): return sftp.close() def on_sftp_closed(_): return conns[0].close() conns =[] conn_defer = ssh.connect(test_credentials.ssh_hostname, test_credentials.ssh_user, private_key_files=[test_credentials.ssh_privatekey]) conn_defer.addCallback(on_connected) conn_defer.addCallback(on_sftp_open) conn_defer.addCallback(on_sftp_closed) return conn_defer
def _main(listener, fw, ssh_cmd, remotename, python, seed_hosts, auto_nets, background): handlers = [] if helpers.verbose >= 1: helpers.logprefix = 'c : ' else: helpers.logprefix = 'client: ' debug1('connecting to server...\n') if background: helpers.do_syslog = True syslog.openlog('sshuttle') # we're redirecting the standard outputs here early so that # the stderr debug message of ssh subprocess would be # redirected properly # TODO: redirecting stderr of ssh to syslog sys.stdout.flush() sys.stderr.flush() si = file('/dev/null', 'r') so = file('/dev/null', 'a+') se = file('/dev/null', 'a+', 0) os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) si.close() so.close() se.close() try: (serverproc, serversock) = ssh.connect(ssh_cmd, remotename, python) except socket.error, e: if e.errno == errno.EPIPE: raise Fatal("failed to establish ssh session") else: raise
#!/usr/bin/env python from argparse import ArgumentParser import ssh import sys if __name__ == '__main__': arg_parser = ArgumentParser(description='do ls on remote server') arg_parser.add_argument('--host', required=True, help='host name to connect to') arg_parser.add_argument('--user', required=True, help='user name to connect as') options = arg_parser.parse_args() ssh = ssh.connect(options.host, options.user) module_func_defs = '. /apps/leuven/etc/bash.bashrc' cmd = '{0}; module load accounting; gbalance'.format(module_func_defs) _, stdout, stderr = ssh.exec_command(cmd) for line in stdout: print(line.rstrip()) for line in stderr: print(line.rstrip(), file=sys.stderr) ssh.close()
def test_live_givenRaspberryPi_internal_whenDefaultCredentials(self): self.assertEquals( -1, ssh.connect(self.localRaspberryPiIp, 'pi', 'raspberry'))
def test_live_givenRaspberryPi_internal_whenInvalidPassword(self): self.assertEquals(-1, ssh.connect(self.localRaspberryPiIp, 'pi', 'blah'))
def test_live_givenRaspberryPi_internal_whenInvalidUsername(self): self.assertEquals( -1, ssh.connect(self.localRaspberryPiIp, 'blah', 'raspberry'))
# sys.exit(0) count = 1 for host in host_list: print '------------------------------------------------------------------pubulis number [ %s ]---------------------------------------------------------------------' % count username = "" password = "" passinfo = '\'s password:'******'' git_pass = '' test_env = False ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, 22, username, password, timeout=5) chan = ssh.invoke_shell() buff = '' # print cmd_result(chan) if test_env: cd_cmd = 'cd /test_code_path/' else: cd_cmd = 'cd /code_path/' chan.send(cd_cmd + '\n') cmd_result(chan) chan.send('sudo ls -lh' + '\n') login_prompt(chan)
#!/usr/bin/env python from argparse import ArgumentParser import ssh import sys if __name__ == '__main__': arg_parser = ArgumentParser(description='do ls on remote server') arg_parser.add_argument('--host', required=True, help='host name to connect to') arg_parser.add_argument('--user', required=True, help='user name to connect as') arg_parser.add_argument('module', help='module to query for') options = arg_parser.parse_args() ssh = ssh.connect(options.host, options.user) module_func_defs = '. /apps/leuven/etc/bash.bashrc; . switch_to_2015a' cmd = '{0}; module av {1}'.format(module_func_defs, options.module) _, stdout, stderr = ssh.exec_command(cmd) for line in stdout: print(line.rstrip()) for line in stderr: print(line.rstrip(), file=sys.stderr) ssh.close()
def test_live_givenRaspberryPi_internal_whenInvalidPassword(self): self.assertEquals(-1, ssh.connect(self.localRaspberryPiIp,'pi','blah'))
def test_live_givenRaspberryPi_internal_whenDefaultCredentials(self): self.assertEquals(-1, ssh.connect(self.localRaspberryPiIp,'pi','raspberry'))
def test_live_givenRaspberryPi_internal_whenInvalidUsername(self): self.assertEquals(-1, ssh.connect(self.localRaspberryPiIp,'blah','raspberry'))
def _main(listener, fw, use_server, remotename): handlers = [] if use_server: if helpers.verbose >= 1: helpers.logprefix = "c : " else: helpers.logprefix = "client: " (serverproc, serversock) = ssh.connect(remotename) mux = Mux(serversock, serversock) handlers.append(mux) expected = "SSHUTTLE0001" initstring = serversock.recv(len(expected)) rv = serverproc.poll() if rv: raise Fatal("server died with error code %d" % rv) if initstring != expected: raise Fatal("expected server init string %r; got %r" % (expected, initstring)) # we definitely want to do this *after* starting ssh, or we might end # up intercepting the ssh connection! fw.start() def onaccept(): sock, srcip = listener.accept() dstip = original_dst(sock) debug1("Accept: %r:%r -> %r:%r.\n" % (srcip[0], srcip[1], dstip[0], dstip[1])) if dstip == listener.getsockname(): debug1("-- ignored: that's my address!\n") sock.close() return if use_server: chan = mux.next_channel() mux.send(chan, ssnet.CMD_CONNECT, "%s,%s" % dstip) outwrap = MuxWrapper(mux, chan) else: outwrap = ssnet.connect_dst(dstip[0], dstip[1]) handlers.append(Proxy(SockWrapper(sock, sock), outwrap)) handlers.append(Handler([listener], onaccept)) while 1: if use_server: rv = serverproc.poll() if rv: raise Fatal("server died with error code %d" % rv) r = set() w = set() x = set() handlers = filter(lambda s: s.ok, handlers) for s in handlers: s.pre_select(r, w, x) debug2("Waiting: %d[%d,%d,%d]...\n" % (len(handlers), len(r), len(w), len(x))) (r, w, x) = select.select(r, w, x) # log('r=%r w=%r x=%r\n' % (r,w,x)) ready = set(r) | set(w) | set(x) for s in handlers: if s.socks & ready: s.callback() if use_server: mux.callback() mux.check_fullness()
def __connect(self, command): result = ssh.connect(self.ip, self.username, self.password, command) return result
__author__ = 'Alexander' import ssh ssh.connect('192.168.1.1', 'pi', 'raspberry')
import ssh import paramiko import datetime import smtplib ssh = paramiko.SSHClient() hostname = "159.89.170.250" username = "" password = "" command = "df -h" ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) x = ssh.connect(hostname, 22, username, password) ssh.invoke_shell() stdin, stdout, stderr = ssh.exec_command(command) x = stdout.read() text_file = open("Output.txt", "a") datex = str(datetime.date.today()) text_file.write(datex) text_file.write("\n") timex = str(datetime.datetime.now().time()) text_file.write(timex) text_file.write("\n") text_file.write(x) text_file.write("***********************\n") text_file.close() fromaddr = '*****@*****.**' toaddrs = '*****@*****.**', '*****@*****.**', '*****@*****.**', '[email protected] ' msg = "\r\n".join([ "To: [email protected]", "Subject: Today's Serever Health", "",
#os.system("sh generateEvalFiles.sh") for i in range(int(startHost), int(endHost)): host = networkPart + '.' + str(i) c = ping.verbose_ping(host) if c > 0: upList.append(host) else: downList.append(host) if len(upList) < 9: print 'Not enough hosts alive. Increase the range' exit() for host1 in upList: sshConnect = ssh.connect(host1,uname,passwd) #sshConnect = sshConnect.get_transport() if sshConnect =='': print 'skipping', host1 else: sshHandlers.append(sshConnect) print "logged into" , host1 if len(sshHandlers) == 9: break for handler in sshHandlers: #Modification to be done: Run all the commands in parallel thread = threading.Thread(target = func, args = (handler,count)) threads.append(thread) thread.start() print 'Command executed, count = ', count
def _main(listener, fw, use_server, remotename, seed_hosts, auto_nets): handlers = [] if use_server: if helpers.verbose >= 1: helpers.logprefix = "c : " else: helpers.logprefix = "client: " (serverproc, serversock) = ssh.connect(remotename) mux = Mux(serversock, serversock) handlers.append(mux) expected = "SSHUTTLE0001" initstring = serversock.recv(len(expected)) rv = serverproc.poll() if rv: raise Fatal("server died with error code %d" % rv) if initstring != expected: raise Fatal("expected server init string %r; got %r" % (expected, initstring)) def onroutes(routestr): if auto_nets: for line in routestr.strip().split("\n"): (ip, width) = line.split(",", 1) fw.auto_nets.append((ip, int(width))) # we definitely want to do this *after* starting ssh, or we might end # up intercepting the ssh connection! # # Moreover, now that we have the --auto-nets option, we have to wait # for the server to send us that message anyway. Even if we haven't # set --auto-nets, we might as well wait for the message first, then # ignore its contents. mux.got_routes = None fw.start() mux.got_routes = onroutes def onhostlist(hostlist): debug2("got host list: %r\n" % hostlist) for line in hostlist.strip().split(): if line: name, ip = line.split(",", 1) fw.sethostip(name, ip) mux.got_host_list = onhostlist def onaccept(): sock, srcip = listener.accept() dstip = original_dst(sock) debug1("Accept: %r:%r -> %r:%r.\n" % (srcip[0], srcip[1], dstip[0], dstip[1])) if dstip == listener.getsockname(): debug1("-- ignored: that's my address!\n") sock.close() return if use_server: chan = mux.next_channel() mux.send(chan, ssnet.CMD_CONNECT, "%s,%s" % dstip) outwrap = MuxWrapper(mux, chan) else: outwrap = ssnet.connect_dst(dstip[0], dstip[1]) handlers.append(Proxy(SockWrapper(sock, sock), outwrap)) handlers.append(Handler([listener], onaccept)) if seed_hosts != None: debug1("seed_hosts: %r\n" % seed_hosts) mux.send(0, ssnet.CMD_HOST_REQ, "\n".join(seed_hosts)) while 1: if use_server: rv = serverproc.poll() if rv: raise Fatal("server died with error code %d" % rv) r = set() w = set() x = set() handlers = filter(lambda s: s.ok, handlers) for s in handlers: s.pre_select(r, w, x) debug2("Waiting: %d[%d,%d,%d]...\n" % (len(handlers), len(r), len(w), len(x))) (r, w, x) = select.select(r, w, x) # log('r=%r w=%r x=%r\n' % (r,w,x)) ready = set(r) | set(w) | set(x) for s in handlers: if s.socks & ready: s.callback() if use_server: mux.callback() mux.check_fullness()
import ssh ssh = ssh.ssh('10.10.88.192', 'Admin', 'admin') ssh.connect() print(ssh.cmd('ls'))
# coding:utf-8 import ssh # 接続情報 HOST = '192.168.43.50' USER = '******' PASS = '******' PORT = 22 # ssh接続 ssh = ssh.SSHClient() ssh.load_system_host_keys() ssh.connect(HOST, username=USER, password=PASS, port=PORT) # コマンド実行 stdin, stdout, stderr = ssh.exec_command('ls -l') # 実行結果出力 for line in stdout.read().split('\n'): print line # 切断 ssh.close()