I am trying to create a program with python,
I wrote code that allows one computer to connect another,
I don't know how I can see the other computer desktop and control it's running programs
ip = "127.0.0.1"
username = ""#"username"
password = ""#"password"
try:
print ("Establishing connection to %s" %ip)
connection = wmi.WMI(ip, user=username, password=password)
connection.Win32_Process.Create(CommandLine="notepad.exe /c text.txt")
print ("Connection established")
except wmi.x_wmi:
print ("Your Username and Password of "+getfqdn(ip)+" are wrong.")
To view the screen, you'll need to use a different protocol. I recommend RDP, because it's already installed on Windows computers. You can use the rdpy module to do this.
As for seeing what programs are running, there's probably some way to list currently running processes but I can't find it either.
Related
I have created GuI in Visual Studio 2019.
There user will enter username and password and that i have to pass to python script. That when user will click on login button, python script will be triggered and output will be displayed.
My Tried python code is:
import paramiko
import time
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
hostname = input("Enter host IP address: ")
username = input("Enter SSH Username: ")
password = input("Enter SSH Password: ")
port = 22
ssh.connect(hostname, port, username, password, look_for_keys=False)
print("ssh login successfully")
#stdin,stdout,stderr = ssh.exec_command('show version')
#output = stdout.readlines()
#print(output)
Device_access = ssh.invoke_shell()
Device_access.send(b'environment no more \n')
Device_access.send(b'show version\n')
time.sleep(2)
output = Device_access.recv(65000)
print (output.decode('ascii'))
except:
print("error in connection due to wrong input entered")
But in this i am not getting how to link with input enter to Gui c# with python script. Please let me know how i can do.
Thanks in advance!
You could use arguments to call your Python Script.
Change the python script:
import paramiko
import time
import sys # Used to get arguments
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
hostname = sys.argv[1] # Skip 0th arg, since it is just the filename
username = sys.argv[2]
password = sys.argv[3]
port = 22
ssh.connect(hostname, port, username, password, look_for_keys=False)
print("ssh login successfully")
#stdin,stdout,stderr = ssh.exec_command('show version')
#output = stdout.readlines()
#print(output)
Device_access = ssh.invoke_shell()
Device_access.send(b'environment no more \n')
Device_access.send(b'show version\n')
time.sleep(2)
output = Device_access.recv(65000)
print (output.decode('ascii'))
except:
print("error in connection due to wrong input entered")
And change your C# code which calls the Script to something like this:
Process pythonScript = new Process();
pythonScript.StartInfo.FileName = "Your python script";
pythonScript.StartInfo.Arguments = $"{YouHostnameVar} {YouUsernameVar} {YourPasswordVar}"; // Start the script with the credentials as arguments
pythonScript.Start();
There are multiple approaches to incorporating a Python script with .NET C# code
I will try and give a basic overview, along with my suggestion, but ultimately, it will be up to you to figure out what works best.
IronPython
IronPython is an actual separate interpreter to translate Python code into the .NET Common Language Runtime (CLR). It works well for simple Python2 scripts that are not reliant on certain libraries.
Python.NET
Python.NET uses the normal Python interpreter. It simply provides a way to interface between Python scripts and .NET code.
System Diagnostics (My Suggestion)
The System Diagnostics C# tool allows you to run Python scripts as a system process. Not that this only runs the Python script. In order to transfer information between the Python script and the C# code, you will need some kind of shared file. I recommend setting up a folder where you save information used by both the C# and Python programs.
For a simple implementation of System Diagnostics, along with notes on the particular way System Diagnostics is being called, check out this: https://www.dotnetlovers.com/article/216/executing-python-script-from-c-sharp
EDIT Based on Paul Sütterlin Answer
As opposed to using a file to share information, Paul correctly points out that you can pass information as arguments. He also points out the simple process tool in C#, which is easier to set up than System Diagnostics. I recommend you read the article I linked to see which solution best suits you. System diagnostics gives you more options, but they do have to be configured.
I am currenlty using machine A and I am trying to access machine B via Python to copy files from machine B to machine A.
I have already tried the methods explained here How to connect to a remote Windows machine to execute commands using python? , but with no luck as I cannot manage to even get access to the remote machine.
I am open to other solutions, even better if using Python 3+.
Here is an example of the code in use.
ip = r'\\IP.IP.IP.IP'
username = r'AccountUserName'
password = r'AccountPassword'
# -------------------------------- with win32net
import win32net
import win32file
data = {
'remote': r'\\IP.IP.IP.IP\C$',
'local': 'C:',
'username': username,
'password': password
}
win32net.NetUseAdd(None, 2, data)
# -------------------------------- with wmi
import wmi
from socket import *
try:
print ("Establishing connection to %s" %ip)
connection = wmi.WMI(ip, user=username, password=password )
print ("Connection established")
except wmi.x_wmi:
print ("Your Username and Password of "+getfqdn(ip)+" are wrong.")
Using the win32net method
According to the documentation here https://learn.microsoft.com/en-us/windows/win32/api/lmuse/nf-lmuse-netuseadd
If the function is to be run from the same computer the script is running from (A), then the first parameter f NetUseAdd can be left to NONE, but with that I get the error
pywintypes.error: (87, 'NetUseAdd', 'The parameter is incorrect.')
Whilst if I change it with "127.0.0.1" I get the error
pywintypes.error: (50, 'NetUseAdd', 'The request is not supported.')
And lastly, if I change it with the same IP that I am trying to access I get the error
pywintypes.error: (1326, 'NetUseAdd', 'Logon failure: unknown user name or bad password.')
Using the wmi method
It gives the error
Your Username and Password of \\IP.IP.IP.IP are wrong.
There can be multiple ways to achieve this. One of them is given below which makes use of inbuilt windows utilities.
import os
machine_b = {"ip":"10.197.145.244","user":"administrator","pwd":"abc1234"}
src = r"C:\Temp" # folder to copy from remote machine
dest = r"C:\Python27\build\temp" # destination folder on host machine
network_drive_letter = "Z:"
source_driver_letter = os.path.splitdrive(src)[0][0]
cmd = "netuse %s \\%s\%s$ %s /u:%s"%(network_drive_letter, machine_b["ip"],source_driver_letter,machine_b["pwd"],machine_b["user"])
os.system(cmd)
cmd = "robocopy %s %s /mir"%(src.replace(source_driver_letter,network_drive_letter),dest)
os.system(cmd)
You can improve this code by handling exceptions and replacing os.system with subprocess.Popen calls.
Note: Be careful with /MIR switch as it can copy as well as delete files in the host machine. It creates mirror of destination folder.
I am new to Python and I am trying to make a script that connects to a remote windows machine and change mdb file there. I can’t figure out how to work with the WMI library.
When I need to change mdb file (Access database) on my machine, I just use pyodbc connect. For example like this:
connStr = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb)};'
r'DBQ=C:\Komax\Data\Topwin\DatabaseServer.mdb;')
cursor = connStr.cursor()
But now I need to run code on my machine so that it modifies the file (mdb) on the other machine. It seems like I have to use this code below to connect to remote machine, but I don't know what to do next, how to use connection. Please, help me to solve the problem :)
ip = "192.168.18.74"
username = "admin"
password = "komax"
from socket import *
try:
print("Establishing connection to %s" % ip)
connection = wmi.WMI(ip, user=username, password=password)
print("Connection established")
except wmi.x_wmi:
print("Your Username and Password of "+getfqdn(ip)+" are wrong.")
I'm currently working a server-client setup in which I have two separate server scripts. One python script is responsible for running a SSH listener with Paramiko, and that script runs on one machine. I have another server script specifically acting as an SFTP server on another, separate machine, within the same range and subnet as the other one.
My client code is running on a windows 10 system. Both servers are running in unix environments (macOS and Ubuntu 16.04 respectively).
The SFTP server that I am running is aptly titled sftpserver, and is available at https://github.com/rspivak/sftpserver/.
The below code is actually the entirety of my client.py as it stands, minus the import statements.
key = paramiko.RSAKey.from_private_key_file('testkey.key')
transport = paramiko.Transport(('192.168.1.116', 10000))
transport.connect(username='root', password='toor', pkey=key)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.1.107', username='root', password='toor')
chan = client.get_transport().open_session()
chan.send("Hey man! I'm connected!")
print(chan.recv(1024))
def sftp(localpath, name):
try:
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(localpath, '/root/uploads/' + name)
sftp.close()
transport.close()
return "<+> Done uploading"
except Exception as e:
return str(e)
while True:
command = chan.recv(1024).decode()
ipdb.set_trace() // <-- debugging purposes only
if 'grab' in command:
_, path, name = command.split(' ')
chan.send(sftp(path, name))
else:
try:
CMD = subprocess.check_output(command, shell=True)
chan.send(CMD)
except Exception as e:
chan.send(str(e))
client.close()
Executing the grab command in my script looks like this:
grab C:\Users\xxx\testing.txt testing.txt
Now, if I write a path exactly like that (with the back slashes), it will append a second back slash after each one. So, the path I supplied now looks like C:\\Users\xxx\\testing.txt, and this is what I imagine is causing me to receive File not found errors. Thanks to pdb I was able to find this issue, but I am unsure how to continue. In all honesty, I am completely unsure if this problem is paramiko related or if it's some weird python behavior that I haven't encountered yet.
Also, sorry for no stack trace. I'll try to obtain one if possible, but I'm a bit pressed for time right this second.
I am trying to ssh to a test cisco router in a test environment using python paramiko, and run cisco commands in that test router.
Everything works great except for 1 small detail.
After running the script I want the ssh session to remain open. (so I can run other commands manually).
I want to keep the ssh session open until I type "exit"
I found another link with a similar issue but I cant understand the solution.
(See here Python ssh - keep connection open after script terminates)
I would appreciate if someone can help me out here
My code
import paramiko
import time
def ssh_session(ip):
try:
session = paramiko.SSHClient() #Open the session
session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
session.connect(ip, username = "ciscouser1", password = "password")
connection = session.invoke_shell()
####Running Cisco IOS commands###
connection.send("enable\n")
connection.send("password1") #sending
connection.send("\n")
connection.send("configure terminal\n\n")
time.sleep(1)
connection.send("do show ip int brief\n")
time.sleep(1)
except paramiko.AuthenticationException:
print "wrong credentials"
ssh_session("10.10.10.1")
The session timeout would be controlled by the SSH server. To the best of my knowledge, the only way to keep your session alive on the client side is to not be inactive, which can be accomplished by sending null packets. As to how to do this specifically with paramiko I am not certain. Perhaps you could send some kind of dummy command (or maybe even an empty string?) every so often?