Execute python script on remote server from another script - python

import os
import sys
import commands
os.system('cat disk_space.py | ssh niraj#abc python - "sys.argv[1]"')
O/P:
python: No match.
Any idea ?

Directly run python script in your server, listen some one port which is not be used. when the port receive a signal, run the script which you want execute.
How to create socket service:
def tcplink(sock, addr):
print('Accept new connection from %s:%s...' % addr)
sock.send(b'Welcome!')
while True:
data = sock.recv(1024)
time.sleep(1)
if not data or data.decode('utf-8') == 'exit':
break
# execute what you want
sock.close()
print('Connection from %s:%s closed.' % addr)
Keep service alive in your server.

Related

How to create Python API or network requests hidden (protected from hackers checking network traffic) on Local Network to manage Computers

I know that I can see inside of network traffic for example with WireShark. When i use GET on HTML I can see those stuff in URL, what should not be problem what I am doing. But I believe GET,POST and maybe REQUEST too, as I did not work with that one yet can bee seen on something like Wire Shark network analyzer.
I am making Python client, what i will put on computers in network to show their IP,Host Name and Users on PC. This client will be as gate to the computer for remote control. As our management does not want to spend money for windows server, or other management system we need to get something free to manage all computers.
I am also seeking advice how I could do it as you are more skilled then me here.
I found few ways.
With the client create SSH Gateway for receiving commands.
With Client enable the Powershell remote option, then just push scripts to all computers at once.
Use some way the API requests etc... I am not skilled in this one at all, but I believe this is the way how other similar programs works?
As this client would create big security risk, I am first seeking way what is best way to hide it from network. Probably I will need to come up with some Private and public Key system here as well.
What are yours suggestions please on this topic?
here is just very short code I am playing with to receive basic info as IP, Host name and all Users
the Flask website showing those values is just for test, It will not be there once it is deployed
Update
I took advice from MarulForFlask but I got a couple issues. First this i think can have only one connection at a time. And second if possible Can i get the output of console from the client PC on screen of Server PC?
I want this output only for testing, as I know if i do something like netstat or any other command with multiple clients it would filled up screen with too many text... Currently I am getting back text format as plaintext with \r \n ... and other text deviders.
I am now trying Multicast, but i am getting error for binding the multicast IP.
OSError: [WinError 10049] The requested address is not valid in its context
Master.py
import time
import socket
import sys
import os
valueExit = True
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = socket.gethostname()
BUFFER_SIZE = 1024
# Initialize the port
port = 8080
# Bind the socket with port and host
s.bind(('', port))
print("waiting for connections...")
# listening for conections
s.listen()
# accepting the incoming connections
conn, addr = s.accept()
print(addr, "is connected to server")
def send_query():
keepAllive, repeatIt = True, False
print("""To exit session write: EndSession
For help write: help
""")
while (keepAllive == True):
# commands for server use only
innerCommands = ["endsession", "help"]
# take command as input
command = input(str("Enter Command : "))
if command not in innerCommands:
conn.send(command.encode())
print("Command has been sent successfully.")
keepAllive = False
repeatIt = True
elif (command == "endsession"):
conn.send(command.encode())
valueExit = False
elif (command == "help"):
print("""To exit session write: EndSession""")
while (repeatIt == True):
# recieve the confrmation
data = conn.recv(BUFFER_SIZE)
if data:
print(f"command recieved and executed sucessfully.\n {data}")
keepAllive = True
repeatIt = False
else:
print("No reply from computer")
keepAllive = True
repeatIt = False
while valueExit == True:
send_query()
Slave.py
import time
import socket
import sys
import subprocess
import os
stayOn = True
def establishConnection():
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = "127.0.0.1"
# Initiaze the port
port = 8080
keepAlive = True
try:
# bind the socket with port and host
s.connect((host, port))
print("Connected to Server.")
while keepAlive == True:
# recieve the command from master program
command = s.recv(1024)
command = command.decode()
# match the command and execute it on slave system
if command == "endsession":
print("Program Ended")
keepAlive = False
elif command != "":
# print("Command is :", command)
#s.send("Command recieved".encode())
proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
s.send(f"{out}".encode())
print("program output:", out)
except Exception as err:
print(f"Error: {err}")
s.send(f"Error: {err}".encode())
while stayOn == True:
establishConnection()
see:
https://www.pythonforthelab.com/blog/how-to-control-a-device-through-the-network/
There uses a flask webserver.
otherwise, create a master.py file and paste this code:
import time
import socket
import sys
import os
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = socket.gethostname()
# Initialize the port
port = 8080
# Bind the socket with port and host
s.bind(('', port))
print("waiting for connections...")
# listening for conections
s.listen()
# accepting the incoming connections
conn, addr = s.accept()
print(addr, "is connected to server")
# take command as input
command = input(str("Enter Command :"))
conn.send(command.encode())
print("Command has been sent successfully.")
# recieve the confrmation
data = conn.recv(1024)
if data:
print("command recieved and executed sucessfully.")
open a slave.py and paste this code:
import time
import socket
import sys
import os
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = "127.0.0.1"
# Initiaze the port
port = 8080
# bind the socket with port and host
s.connect((host, port))
print("Connected to Server.")
# recieve the command from master program
command = s.recv(1024)
command = command.decode()
# match the command and execute it on slave system
if command == "open":
print("Command is :", command)
s.send("Command recieved".encode())
# you can give batch file as input here
os.system('ls')
open slave.py in client, master.py in server
https://www.geeksforgeeks.org/how-to-control-pc-from-anywhere-using-python/

python processes script not returning the same answer as direct bash command

hey first time question asker hope this is the correct format
i have a python scirpt which is trying to basically to use a bash command in this case telnet
this is the script
import subprocess
proc = subprocess.Popen(['/bin/bash'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout = proc.communicate('telnet 192.168.1.67 5555')
print (stdout)
i have a script on my other machine listening on port 5555
and the calling the script in bash returns
Connection closed by foreign host.
("Trying 192.168.1.67...\nConnected to 192.168.1.67.\nEscape character is '^]'.\n", None
and my other computer recognizes a connection but it closes the connection immediately
while when i run the command
telnet 192.168.1.67 5555
it works fine and keeps the connection open
my question is how to i write a script which dose the same thing as the command "telnet 192.168.1.67 5555" and keeps the connection open?
You can use socket — Low-level networking interfac
See the Python module of the week about socket.
Python 2 Example:
import socket, select, string, sys
if(len(sys.argv) < 3) :
print 'Usage : python telnet.py hostname port'
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try :
s.connect((host, port))
except :
print 'Unable to connect'
sys.exit()
print 'Connected to remote host'
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
#incoming message from remote server
if sock == s:
data = sock.recv(4096)
if not data :
print 'Connection closed'
sys.exit()
else :
#print data
sys.stdout.write(data)
#user entered a message
else :
msg = sys.stdin.readline()
s.send(msg)

Socket programming for multiple clients

I'm trying to write code for a chat server using sockets for multiple clients. But it is working for only a single client. Why is it not working for multiple clients?
I have to perform this program using Beaglebone Black. My server program will be running on beaglebone and normal clients on gcc or terminal. So I can't use multithreading.
#SERVER
import socket
import sys
s=socket.socket()
s.bind(("127.0.0.1",9998))
s.listen(10)
while True:
sc,address = s.accept()
print address
while True:
msg = sc.recv(1024)
if not msg:break
print "Client says:",msg
reply = raw_input("enter the msg::")
sc.send(reply)
sc.close()
s.close()
#CLIENT
import socket
import sys
s= socket.socket()
s.connect(("127.0.0.1",9998))
while (1):
msg = raw_input("enter the msg")
s.send(msg)
reply = s.recv(1024)
print "Server says::",reply
s.close()
Use an event loop.
Integrated in python like asyncio : Echo server example
or use an external library that provides the event loop like libuv: Echo server example.
Note: Your code is not working for multiple clients simultaneously beacause you are blocked in the receive operation and you are not handling new accept operations.

Connect to Socket on localhost

I have trouble connecting to my own socket on localhost.
s.connect(('127.0.0.1', 4458)) (or "localhost") will just take forever,
and eventually timeout with TimeoutError: [Errno 110] Connection timed out
It should open port 4458, another script will then send some chars to it. Both scripts are supposed to run on the same Raspberry Pi, while 'server' one will execute with sudo (to access the GPIOs) and one without, being a chat bot.
I have no trouble running the server on the Pi (with python 3.4.1) and the client on my Laptop (mac, python 3.4.2).
Also it does work in reverse direction, server script on the laptop and client on the Raspberry.
As final test, it works with both, the server and the client on the said macbook.
Just server + client on the Pi does not work.
The program freezes
My shortened code if it helps:
# $ sudo python3 server.py
__author__ = 'luckydonald'
import socket # server
import time # wait for retry
import threading
class Server(threading.Thread):
port = 4458;
QUIT = False
def run(self):
s = socket.socket()
failed = True
print ("Starting Server on Port %d" % (self.port))
while failed:
try:
s.bind(("", self.port))
except Exception as err:
print(err)
print("Port assignment Failed. Retring in 1 second.")
time.sleep(1)
else:
failed = False
print("Success.")
while not self.QUIT:
print("Listening!")
conn, addr = s.accept() # freezes here
print("Got something: %s , %s" %(str(conn), str(addr)))
while not self.QUIT:
result = conn.recv(1)
print("Got result: " + str(result))
server = Server();
server.daemon = True
server.run();
# server.start();
And for the client:
# python3 cilent.py
s = socket.socket()
print("connecting...")
s.connect(("localhost",4458)) # also tried "172.0.0.1" # freezes here
print("connected!")
s.sendall("+".encode("utf-8"))
s.sendall("-".encode("utf-8"))
s.close()
It will result in this:
What I didn't expected was that localhost/127.0.0.1 did not work.
100% package loss
I had a malformatted entry in my hosts file.
You should check for below items
there is an installed internet information services
iis is running
firewall is grants required ports for running the python.exe

Connection refused with python sockets

So I am trying to make a server program that will call the client program. The server client work fine if I call them myself from the command line but the connection is refused when the server calls it. Why is this not working?
This is the server code:
import socket,os
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
os.remove("/tmp/SocketTest")
except OSError:
pass
s.bind("/tmp/SocketTest")
os.system("python compute.py")#compute is the client
#execfile('compute.py')
s.listen(1)
conn, addr = s.accept()
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
This is the client code:
import socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("/tmp/SocketTest")
s.send('Hello, world \n')
s.send('its a mighty fine day')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
os.system will run the command you give it to completion, and you’re doing this before you call listen. As such, the client will try to connect to the server before it’s listening. Only once the client exits will the server move on past that line of code to actually start listening and accepting connections.
What you probably want to do is after the call to listen, but before the call to accept (which is when you start blocking), use subprocess.Popen to spawn a subprocess and do not wait on it.
I think the error is that you're calling compute.py before calling listen.
os.system will block your server until the call to python compute.py is completed.
Try subprocess.Popen to spawn the call to compute.py in parallel to your server in a non blocking manner. Callingsubprocess.Popen will launch python compute.py in a new process, and will continue executing the next line conn, addr = s.accept() )
#!/usr/bin/env python
import socket
import os
import subprocess
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
os.remove("/tmp/SocketTest")
except OSError:
pass
s.bind("/tmp/SocketTest")
s.listen(1)
sp = subprocess.Popen(["/usr/bin/env", "python", "compute.py"])
conn, addr = s.accept()
while 1:
data = conn.recv(1024)
if not data:
break
conn.send(data)
conn.close()
That outputs:
Received 'Hello, world \nits a mighty fine day'

Categories