Skip to content

Instantly share code, notes, and snippets.

@queercat
Last active December 31, 2017 04:34
Show Gist options
  • Select an option

  • Save queercat/567ad5d66e47a21c2c8542bef80d8ed5 to your computer and use it in GitHub Desktop.

Select an option

Save queercat/567ad5d66e47a21c2c8542bef80d8ed5 to your computer and use it in GitHub Desktop.
Server and client to a sort of SSH like python connection.
# Client.py a client component to the server component!
import socket # For network stuff obv.
import argparse # Parse arguments!
parser = argparse.ArgumentParser(description = 'Connect to a server and send commands and files to be executed.') # Create the parser.
parser.add_argument('-u', nargs = 1, type = str, help = 'Target destination, e.g. (192.168.2.1., 127.0.0.1') # Add the target.
parser.add_argument('-p', nargs = 1, type = int, help = 'The port for the target destination e.g. 80, 22, 8080.') # Add the port.
parser.add_argument('-f', nargs = 1, type = str, help = 'Optional file to be sent to the server.')
args = vars(parser.parse_args()) # Parse the arguments.
target = args['u'][0] # Retrieve the target dest.
port = args['p'][0] # Retrieve the port.
try:
file = args['f'][0] # Retrieve the (optional) file.
except:
file = '' # Set the file to nothing.
s = socket.socket() # Create the socket object.
# if file != '': # Send file and do execution code.
s.connect((target, port)) # Connect to the target.
print 'Writing to server, write empty line to exit.'
while True:
line = raw_input()
if line == '':
break
s.sendall(line)
while True:
data = s.recv(1024)
if not data:
break
print '%s\n' % (data)
break
s.close() # Close the connection.
# Server.py -- Server for recieving commands, retreiving info etc.
# Example, Client[test.py] --> Server, Server exec test.py > output, Server[output]
import socket
import argparse
import subprocess
parser = argparse.ArgumentParser(description = 'Spin up a server to recieve and execute commands / files.') # Create the parser.
parser.add_argument('-p', nargs = 1, type = int, help = 'Port to listen on.')
args = vars(parser.parse_args())
host = '0.0.0.0' # Listen on all interfaces.
port = args['p'][0] # Port to recieve connections from.
s = socket.socket() # Create a socket.
s.bind((host, port)) # Bind to a host and a port.
s.listen(5) # Listen on max of 5 queues.
print 'Listening to host %s on port %d' % (host, port)
# Server foreeeever.
while True:
client, addr = s.accept()
print 'Now serving client --> %s' % (addr[0])
while True:
data = client.recv(1024)
if not data:
break
print 'Recv: %s' % (data)
try:
client.sendall(str(subprocess.check_output(data, shell = True)))
except:
client.sendall('Command not valid.')
s.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment