This question already has answers here:
I need to securely store a username and password in Python, what are my options? [closed]
(8 answers)
Closed 6 years ago.
So this is my code: https://github.com/trisimix/serialcontrol/blob/master/serialcontrol.py
import subprocess
import os
import stat
dmi = subprocess.check_output('dmidecode', shell=True)
#print(variable)
#run program once as root then cron it as root
try :
file = open("/var/log/serialcontrol/dmidecode.txt", "r")
file.close()
except FileNotFoundError:
script = '/var/tmp/serialcontrol.bash'
with open(script, 'w') as file:
file.write("#!/bin/bash/\nif [ ! -d /var/log/serialcontrol/ ]\nthen\n\tmkdir /var/log/serialcontrol/\nfi");
#st = os.stat(script)
#os.chmod(script, st.st_mode | stat.S_IEXEC)
subprocess.call(["bash", script])
subprocess.call(["rm", script])
#with open('/var/log/serialcontrol/dmidecode.txt' , 'w') as file:
# file.write(dmi);
file = open("/var/log/serialcontrol/dmidecode.txt" , "w");
dmi = str(dmi)
dmi = dmi.replace('\\n', '\n')
dmi = dmi.replace('\\t', '\t')
file.write(dmi)
file.close()
script2 = '/var/log/serialcontrol/serialcontro1.bash'
#with open(script2, 'w') as file:
# file.write('#!/bin/bash\nrecipients="archmachine9#gmail.com"\nsubject="...Subject..."\necho -e "to: $recipients\nsubject: $subject\n"| (cat - &&uuencode /var/log/serialcontrol/dmidecode.txt) | ssmtp archmachine9#gmail.com')
import smtplib
sender = 'archmachine9#gmail.com'
receivers = 'archmachine9#gmail.com'
message = "\r\n".join([
"From: archmachine9#gmail.com",
"To: archmachine9#gmail.com",
"Subject: SerialControl",
"",
dmi
])
username = 'archmachine9#gmail.com'
password = ''
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(sender, receivers, message)
server.quit()
#subprocess.call(["bash", script2])
#this sub is supposed to /n with actual /n's
#subprocess.run(["sed -i 's/\\n/\n/g' /var/log/serialcontrol/dmidecode.txt"], shell=True)
#except FileNotFoundError:
#file = open('/var/tmp/serialcontrol.bash', 'w')
#file.write("#!/bin/bash/\nif [ ! -d /var/log/serialcontrol/]\nthen\n\tmkdir /var/log/serialcontrol/\nfi");
#file.close()
#st = os.stat("/var/tmp/serialcontrol.bash")
#os.chmod("/var/tmp/serialcontrol.bash", st.st_mode | stat.S_IEXEC)
#subprocess.call("/var/tmp/serialcontrol.bash")
I know it's really, really, really, really, REALLY, bad but in the password segment I have to type my password before I cron this script and the password gets stored as plaintext, how fix?
As you tagged the question with bash I shall assume that you use a Linux or Unix-like system.
That is what I would call a machine password. If you want it to be used from a script launched via cron, it must be accessible somewhere on the disk.
The correct (or less bad) way is to:
use a dedicated mail account for that usage - not you personal mail account (but archmachine9 is a hint that you have already done that...) - ideally it should be impossible to login with this account (a single*` in the password field for example)
use a system account on the machine - neither root nor you main local account
store the password in a file located under the home directory of that system account. The password should be read/write only for owner
extract the username, password and eventually server from the environment
if you cannot find one of them, read them from the file
alternatively embed the script in a launcher that read the credentials from the file, and put them in the environment before starting the real script (my favorite option)
That way, even if the mail account is shared over different scripts, you will have one central point to change the password, and as it is stored in a file only accessible to a system account, only the machine admin (root) should be able to read it. And you do not have to know it to develop, maintain and test the script, you will just have to put a test mail account in your dev environment
TL/DR: the password has to be stored as plaintext on the machine for the script to be launchable via cron, but it shall not be in the script itself
Related
I am new to Python and sorry for my bad english.
I'm trying to save a file "toto.txt" from my HDD "d:" to my Synology NAS.
So I'll use paramiko for this, here is the code :
import paramiko
import os
ip_address = "my nas ip"
username = "my username"
password = "mypass"
utilisateur = os.getenv("USERNAME") // to get Windows username
remote_path = f"{utilisateur}/test.txt" // the file downloaded
local_path = "d:/toto.txt" //the file stored on my pc
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip_address,username=username,password=password)
print("Connexion OK >", ip_address)
stdin, stdout, stderr = ssh_client.exec_command(f'mkdir {utilisateur}') //creating folder for the
user
sftp = ssh_client.open_sftp()
sftp.put(local_path,remote_path) // trying to send the file
sftp.close()
ssh_client.close()
i am not getting error but nothing is happening.
The folder is successful created but no file is sending in it.
Have someone an idea?
thanks a lot
If Paramiko does not throw any error, the upload was successful. The file just possibly ended in different location than you wanted/than you look to.
At least for a test, if not permanently, try an absolute absolute path. Make no guesses, use the exact path you see in your GUI SFTP client.
Another possibility is that the server automatically processes the uploaded file somehow and moves it away.
I'm modifying a script in python to run in securecrt 8.5.2 in order to backup the running-config of some cisco ASR9K equipment I have in charge, but the script seems to end abruptly after the second sucessful ssh2 hop (2nd tab) and does not send the commands I scripted (the exit in this specifical example), here's the code I have, as I'd said it's a modified version of the one's in vandyke page for opening ssh2.
One important thing is that I have to tab each session of each individual routers, because it doesn't permit doing an ssh direct from the active cli, so I had to improvise and implement this "connect in TAB", I'm suspecting that the secureCRT doesn't know if it is in the new tab I've opened so, it doesn't know where to send the commands.
I was playing with the line 30, but it doesn't seem to have any effect. I was changing the expected text, but it doesn't seem to recognize the correct tab or doesn't read the correct one.
Personal Background: A complete beginner in the python language.
# $language = "python"
# $interface = "1.0"
# Connect to an SSH server using the SSH2 protocol. Specify the
# username and password and hostname on the command line as well as
# some SSH2 protocol specific options.
host = "X.X.X.a"
host2 = "X.X.X.b"
def main():
crt.Screen.Synchronous = True
# Prompt for a username and password instead of embedding it in a script...
#
usr = crt.Dialog.Prompt("Enter the user name for" + host, "Username", "", True)
passwd = crt.Dialog.Prompt("Enter TACACS+ for" + host, "Login", "", True)
# Build a command-line string to pass to the Connect method.
cmd = "/SSH2 /L %s /PASSWORD %s /C AES-128-CTR /M SHA1 %s" % (usr, passwd, host)
crt.Session.Connect(cmd)
crt.Screen.WaitForString("X.X.X.a#")
crt.Screen.Send("copy running-config tftp:\r")
crt.Screen.WaitForString("Host name or IP address (control-c to abort): []?")
crt.Screen.Send("tftpserver.com\r")
crt.Screen.WaitForString("Destination file name (control-c to abort): [running-config]?")
crt.Screen.Send("X.X.X.a_running_config\r")
crt.Screen.WaitForString("X.X.X.a")
cmd2 = "/SSH2 /L %s /PASSWORD %s /C AES-128 /M SHA1 %s" % (usr, passwd, host2)
crt.Session.ConnectInTab(cmd2)
crt.Screen.WaitForString("X.X.X.b#")
crt.Screen.Send("exit\r")
main()
crt.Session.ConnectInTab(cmd2)
It connects to the equipment in a new tab, but what I expect is that the script will keep doing the same it did for the host1 (X.X.X.a) and send the same boring stuff to the host2 (X.X.X.b) via ssh2 tab, and continue the itterative process until I do this for all the equipments I need.
Thanks for reading me.
Well it's not even funny easy was to solve this very sub-optimal code or script but it was not much of a problem, the only thing is that I had to dissconect to the previous session when I inyected all the commands, so in order to put the cursor on the new tab, the previous session must be dissconected first.
The solution?
crt.Session.Disconnect()
I am trying to write a python script which uses scp to log into a HPC cluster (where I have an account) and transfer files from the cluster to my local system. I am able to os.system() to type the scp command. But, after that, I am a bit confused about what I must do when I am asked for the password (assume my password is password). I have tried os.system('password') and print 'password', but they don't work.
This is the python script that I have written:
import os
import sys
password = 'password'
clusterpath = 'myname#cluster.hpc1.cs.univ.edu:/Projects/re* '
localpath = 'Projects/.'
os.system('scp ' + clusterpath + localpath)
When I execute this script, I am asked for the password of my cluster. How can I enter the password of the cluster account through this python script?
I am working on a project that requires us to upload a vile via SFTP to a remote server, and we are having troubles doing this. We tried following this youtube guide, but we are having some issues.
We are getting a "no such file" error when we run the script, and we know for sure that the file exists and that we have given the python script the right name and location for the file.
This is the script as we have it right now:
import pysftp as sftp
def sftpTry():
try:
s = sftp.Connection(host='babbage.cs.missouri.edu', username ='<username>', password = '<password>')
remotepath = '~it3001s14grp1/videos/newVideo/new.avi'
#localpath = '/etc/motion/capture/hello.txt'
localpath = '/etc/motion/capture/06--2014-05-15---16-16-25.avi'
s.put(localpath, remotepath)
s.close()
except Exception, e:
print str(e)
sftpTry();
You should begin your remote path with a forward slash "/". Also, check the directory you are specifying in the remotepath. You should try to do a pwd in the directory when you login into the server (say using ssh). The remote-path should be specified exactly like that.
Although you do have the filename name in the remote path, it would throw an error if you specify just the folder's name.
Another tip would be to use getpass instead of hard-coding the password:
passwd = getpass.getpass()
s = sftp.Connection(host='<host>', username = '<username>', password = passwd)
I am sure this has been resolved before but I cannot seem to find a similar Q&A (newbie)
Using Windows XP and Python 2.5, I m trying to use a script to connect to an FTP server and dowload files. It should be simple but following the instructions of similar scripts I get the errors:
ftp.login('USERNAME')
File "C:\Python25\lib\ftplib.py", line 373, in login
if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
File "C:\Python25\lib\ftplib.py", line 241, in sendcmd
return self.getresp()
File "C:\Python25\lib\ftplib.py", line 216, in getresp
raise error_perm, resp
error_perm: 530 User USERNAME cannot log in.
The script I use is:
def handleDownload(block):
file.write(block)
print ".",
# Create an instance of the FTP object
# FTP('hostname', 'username', 'password')
ftp = FTP('servername')
print 'ftplib example'
# Log in to the server
print 'Logging in.'
# You can specify username and password here if you like:
ftp.login('USERNAME', 'password')
#print ftp.login()
# This is the directory
directory = '/GIS/test/data'
# Change to that directory.
print 'Changing to ' + directory
ftp.cwd(directory)
# Print the contents of the directory
ftp.retrlines('LIST')
I appreciate this might be a trivial question, but if anyone can provide some insights it would be very helpful!
Thanks, S
I can't understand which library are you using. Python standard urllib2 is sufficient:
import urllib2, shutil
ftpfile = urllib2.urlopen("ftp://host.example.com/path/to/file")
localfile = open("/tmp/downloaded", "wb")
shutil.copyfileobj(ftpfile, localfile)
If you need to login (anonymous login isn't sufficient), then specify the credentials inside the url:
urllib2.urlopen("ftp://user:password#host.example.com/rest/of/the/url")
ftp.login('USERNAME', 'password')
Replace this with real data. According to the error you are trying to login as "USERNAME" with the password "password" which obviously won't work.
Also, replace servername in ftp = FTP('servername')
with the hostname of the server you want to connect to.
the first trivial check would be to open an interactive session (i.e. ftp yourself to this server with the same credentials), to be sure that this is not a permission issue..
Another source of failure, you might need to give your username as domain\username when connecting to a MS ftp server.
Maybe that helps ?