I am new to Python.
I am using Paramiko module to login to the Linux servers. However I have 2 different passwords for authentication and I want the server to be logged in using either of them. In case both fails, I am raising the exception for it.
I am facing problem when I have to use the second password. Here is sample for the same.
server.txt is having the list of servers
file1 = 'D:\Linux\server.txt'
with open(file1) as f:
switch_ip = f.readlines()
switch_ip = [x.strip() for x in switch_ip]
username = "user1"
password1 = "abcd2"
password2 = "efcdrf2"
def simple_out(cmd):
try:
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
x=[]
ssh.connect(IP,port =22,username = username, password = password1 or password2)
pass
time.sleep(2)
stdin, stdout, stderr = ssh.exec_command(cmd)
line1 = stdout.readline() #read line by line
while line1:
split_words = line1.split() #List
# split_words.insert(0,IP)
print split_words
str1 = ' '.join(split_words) #String
x.append(str1)
line1=stdout.readline()
return [x]
except (paramiko.BadHostKeyException, paramiko.AuthenticationException, paramiko.SSHException, socket.error) as e:
time.sleep(2)
buf = StringIO.StringIO(e)
line3 = buf.read()
y=[line3]
return [y]
for IP in switch_ip:
output = simple_out("df -h") # will call function and execute command
out1 = output[0] #t
for items in out1:
book = xlrd.open_workbook('D:\\Linux\\xlwt example.xls')
sheet2 = book.sheet_by_index(0)
row_count = sheet2.nrows
column_count = 1
sheet1.write(row_count, 0, IP)
sheet1.write(row_count, column_count, items)
wb.save('D:\\Linux\\xlwt example.xls')
time.sleep(2)
I want to login to the servers using either of the 2 passwords
you can use try catch block for each password and continue in your program see below example:
try:
ssh.connect(IP,port =22,username = username, password = password1)
except paramiko.AuthenticationException as e: #catch other exceptions as well
ssh.connect(IP,port =22,username = username, password = password2)
I am trying to run the python code in the linux machine where the weblogic server is located whose health status needs to be known. I am passing username and password as per below code. Below is part of the python code:
import urllib2
import httplib
import getpass
import json
import os
import sys
import time
import math
def getServerJson(url, username, password):
req = urllib2.Request(url)
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
try:
response = opener.open(url)
json_string = response.read()
if response.getcode() != 200:
print("")
print("Error connecting to WLS Server!")
print("HTTP Error code = " + str(response.getcode()))
print("URL = "+url)
sys.exit(1)
except urllib2.URLError as e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
except urllib2.HTTPError, e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
except httplib.HTTPException, e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
return json.loads(json_string)
But I am getting below error on giving input:
Please enter the WLS Server Details
Please enter the server and port: IP:PORT
Please enter the weblogic user name: weblogic
Please enter the weblogic user password:
[Errno 111] Connection refused
Please find below the url calling part of the code:
def getServerJson(url, username, password):
req = urllib2.Request(url)
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
try:
response = opener.open(url)
json_string = response.read()
if response.getcode() != 200:
print("")
print("Error connecting to WLS Server!")
print("HTTP Error code = " + str(response.getcode()))
print("URL = "+url)
sys.exit(1)
except urllib2.URLError as e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
except urllib2.HTTPError, e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
except httplib.HTTPException, e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
return json.loads(json_string)
#Get a list of all of the Admin and Managed Servers in the domain
def getServers(wlsDomain,wlsServerUrl,username,password ):
url = 'http://'+wlsServerUrl+'/management/wls/latest/servers'
serverJson = getServerJson(url, username, password)
for server in serverJson["links"]:
if (server['rel'] != "parent"):
wlsDomain.addServer(WLSServer(server["title"], server["uri"]))
# Get the url of the list of logs, along with some other basic
# server information
def getLogListUrl(server, username, password):
serverJson = getServerJson(server.serverUrl, username, password)
server.setState(serverJson["item"]["state"])
if server.state == "running":
server.setHealth(serverJson["item"]["health"]["state"])
for link in serverJson["links"]:
if link["rel"] == "logs":
logListULR = link["uri"]
return logListULR
#For the given server, get the url for each server log
def getServerLogUrl(server,username,password, logListUrl):
logListJson = getServerJson(logListUrl, username, password)
for link in logListJson["links"]:
if link["rel"] == "items.name":
if not link["title"].startswith("JMSMessageLog") and \
not link["title"].startswith("HTTPAccessLog"):
server.addLog(WLLog(link["title"],link["uri"]))
#Go and find all server logs and read them, and take note of
#the error messages
def searchServerLogs(wlsDomain, username, password):
for server in wlsDomain.serverList:
#get the url to the list of logs for the given server
logListUrl = getLogListUrl(server, username, password)
#we can't get the log of a server that is not running
if server.state != "running":
continue
#get the url for each server log of the given server
getServerLogUrl(server,username,password, logListUrl)
for log in server.logList:
#we are not interested in the HTTPAccessLog
if log.name != "HTTPAccessLog":
if server.state != "running":
continue
startTime = time.time()
print("Reading " + server.name + " : " + log.name)
serverLogJson = getServerJson(log.logUrl, username, password)
for logEntry in serverLogJson["items"]:
if logEntry["severity"] == "Error":
log.addLogEntry(LogEnty(logEntry["severity"],logEntry["timeStamp"],logEntry["message"]))
server.incrementError()
endTime = time.time()
log.setDuration(formatTimeOutput(math.floor(endTime-startTime)))
def run():
print("")
print("")
print("Please enter the WLS Server Details")
print("-------------------------------------------")
print("")
wlsServerUrl = raw_input('Please enter the server and port e.g localhost:7001 ')
username = raw_input("Please enter the weblogic user name: ")
password = getpass.getpass("Please enter the weblogic user password: ")
print("")
wlsDomain = WLSDomain()
getServers(wlsDomain,wlsServerUrl,username,password)
searchServerLogs(wlsDomain,username,password)
outputStatisticsConsole(wlsDomain)
writeHTMLOutput(wlsDomain)
According to the official documentation, I have to authenticate with OAuth1 in order to use their API. I can't seem to get all the necessary part to authenticate. Here's my code so far:
#!usr/bin/env python
#encoding=utf-8
import requests
import sys, getopt
import urllib2
LOCALE = 'zh-CN'
LANGUAGE = 'zh-CN'
def doRequest(imageUrl):
reqUrlA = 'https://api.cloudsightapi.com/image_requests/' # get token
reqUrlB = 'https://api.cloudsightapi.com/image_responses/' # get the final recognition result with token
headers = {
'Authorization' : 'CloudSight INSERT API KEY',
'Host' : 'api.cloudsightapi.com',
'Origin:' : 'https://cloudsightapi.com'
}
postData = {
'image_request[remote_image_url]' : imageUrl,
'image_request[locale]': LOCALE,
'image_request[language]': LANGUAGE
}
try:
response = requests.post(reqUrlA, headers=headers, data=postData)
except Exception, e:
print 'Error: connection error, please check your Internet and confirm the image url'
sys.exit()
if "error" in response.json():
# print "Error: %s" % response.json()["error"]
print "无法识别图片:请检查图片的连接是否合法"
print
sys.exit()
else:
token = response.json()['token']
# you may get some response with status 'not completed' for about some times before getting the final result
reqTimes = 20
isNotified = True
while reqTimes > 0:
try:
response = requests.get(reqUrlB + token, headers=headers)
except Exception, e:
print 'Error: connection error, please check your Internet and confirm the image url'
sys.exit()
status = response.json()['status']
if status == 'completed':
print 'RESULT: '
print '\timage url:', imageUrl
print '\timage name:', response.json()['name']
print
# return response.json()['name']
break
elif status == 'not completed':
if isNotified == True:
print 'recognition in progress'
isNotified = False
reqTimes -= 1
def usage():
print '''
usage:
cloudSightAPI ImageURL fdgdfgrtrgd
type `cloudSightAPI -h` to get help
'''
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'h')
for op, value in opts:
if op == '-h':
usage()
sys.exit()
if len(args) == 0:
usage()
sys.exit()
except getopt.GetoptError as e:
print 'Error: using invalid parameter -%s' % e.opt
usage()
sys.exit()
imageUrl = sys.argv[1]
doRequest(imageUrl)
if __name__ == '__main__':
main()
doRequest ("INSERT IMAGE URL")
According to the official documentation, I need to get the oauth_nonce and oauth_token in order to create a signature that would allow me use the api. How would I go about getting these details? Is there a oauth creator available?
Ended up doing it in Ruby. It was a lot easier!
https://github.com/cloudsight/cloudsight-ruby
Hope it will work sorry for the indentation dont forget to import requests
def quest(imageUrl):
fa=''
LOCALE = 'en-US'
LANGUAGE = 'en-US'
reqUrlB = 'https://api.cloudsightapi.com/image_responses/'
header = {
'Authorization' : 'CloudSight API_KEY_HERE',
'Host' : 'api.cloudsightapi.com',
'Origin:' : 'https://cloudsightapi.com'
}
footer = postData = {
'image_request[remote_image_url]' : imageUrl,
'image_request[locale]': LOCALE,
'image_request[language]': LANGUAGE
}
r = requests.post("https://api.cloudsightapi.com/image_requests",headers=header,data=footer)
print r
token = r.json()['token']
status='lol'
while True:
response = requests.get(reqUrlB + token, headers=header)
status = response.json()['status']
if status=='completed':
name=response.json()['name']
fa=name
break
return fa
import ldap
try:
l = ldap.initialize("ldap://ldap.xxxxx.com:389")
username=raw_input("Enter the username : ")
password = raw_input("Enter the password :")
if(username == "" or password==""):
print "Login Error : Username or password can't be blank"
else:
l.simple_bind(username,password)
print "Contact..."
except ldap.LDAPError, e:
print e
baseDn = "ou=active, ou=employees, ou=people, o=xxxxx.com";
searchScope = ldap.SCOPE_ONELEVEL
#retrieve all attributes
retrieveAttributes = None
search_query = raw_input("Enter the query :")
searchFilter = "cn="+search_query
try :
ldap_result_id = l.search(baseDn, searchScope, searchFilter, retrieveAttributes)
result_set = []
while 1:
result_type, result_data = l.result(ldap_result_id, 0)
if(result_data == []):
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
#print result_set
print len(result_set)
except ldap.LDAPError, e:
print e
#print result_set[0]
The above code uses python-ldap to access ldap services. The result_set type is displayed as list but the number of items when using the len() function turns out to be zero. I need to perform operations on the retrieved string.
I want to be able to move an email in GMail from the inbox to another folder using Python. I am using imaplib and can't figure out how to do it.
There is no explicit move command for IMAP. You will have to execute a COPY followed by a STORE (with suitable flag to indicate deletion) and finally expunge. The example given below worked for moving messages from one label to the other. You'll probably want to add more error checking though.
import imaplib, getpass, re
pattern_uid = re.compile(r'\d+ \(UID (?P<uid>\d+)\)')
def connect(email):
imap = imaplib.IMAP4_SSL("imap.gmail.com")
password = getpass.getpass("Enter your password: ")
imap.login(email, password)
return imap
def disconnect(imap):
imap.logout()
def parse_uid(data):
match = pattern_uid.match(data)
return match.group('uid')
if __name__ == '__main__':
imap = connect('<your mail id>')
imap.select(mailbox = '<source folder>', readonly = False)
resp, items = imap.search(None, 'All')
email_ids = items[0].split()
latest_email_id = email_ids[-1] # Assuming that you are moving the latest email.
resp, data = imap.fetch(latest_email_id, "(UID)")
msg_uid = parse_uid(data[0])
result = imap.uid('COPY', msg_uid, '<destination folder>')
if result[0] == 'OK':
mov, data = imap.uid('STORE', msg_uid , '+FLAGS', '(\Deleted)')
imap.expunge()
disconnect(imap)
As for Gmail, based on its api working with labels, the only thing for you to do is adding dest label and deleting src label:
import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)
obj.login('username', 'password')
obj.select(src_folder_name)
typ, data = obj.uid('STORE', msg_uid, '+X-GM-LABELS', desti_folder_name)
typ, data = obj.uid('STORE', msg_uid, '-X-GM-LABELS', src_folder_name)
I suppose one has a uid of the email which is going to be moved.
import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)
obj.login('username', 'password')
obj.select(src_folder_name)
apply_lbl_msg = obj.uid('COPY', msg_uid, desti_folder_name)
if apply_lbl_msg[0] == 'OK':
mov, data = obj.uid('STORE', msg_uid , '+FLAGS', '(\Deleted)')
obj.expunge()
None of the previous solutions worked for me. I was unable to delete a message from the selected folder, and unable to remove the label for the folder when the label was the selected folder. Here's what ended up working for me:
import email, getpass, imaplib, os, sys, re
user = "user#example.com"
pwd = "password" #getpass.getpass("Enter your password: ")
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
from_folder = "Notes"
to_folder = "food"
m.select(from_folder, readonly = False)
response, emailids = imap.search(None, 'All')
assert response == 'OK'
emailids = emailids[0].split()
errors = []
labeled = []
for emailid in emailids:
result = m.fetch(emailid, '(X-GM-MSGID)')
if result[0] != 'OK':
errors.append(emailid)
continue
gm_msgid = re.findall(r"X-GM-MSGID (\d+)", result[1][0])[0]
result = m.store(emailid, '+X-GM-LABELS', to_folder)
if result[0] != 'OK':
errors.append(emailid)
continue
labeled.append(gm_msgid)
m.close()
m.select(to_folder, readonly = False)
errors2 = []
for gm_msgid in labeled:
result = m.search(None, '(X-GM-MSGID "%s")' % gm_msgid)
if result[0] != 'OK':
errors2.append(gm_msgid)
continue
emailid = result[1][0]
result = m.store(emailid, '-X-GM-LABELS', from_folder)
if result[0] != 'OK':
errors2.append(gm_msgid)
continue
m.close()
m.logout()
if errors: print >>sys.stderr, len(errors), "failed to add label", to_folder
if errors2: print >>sys.stderr, len(errors2), "failed to remove label", from_folder
I know that this is a very old question, but any way. The proposed solution by Manoj Govindan probably works perfectly (I have not tested it but it looks like it. The problem that I encounter and I had to solve is how to copy/move more than one email!!!
So I came up with solution, maybe someone else in the future might have the same problem.
The steps are simple, I connect to my email (GMAIL) account choose folder to process (e.g. INBOX) fetch all uids, instead of email(s) list number. This is a crucial point to notice here. If we fetched the list number of emails and then we processed the list we would end up with a problem. When we move an email the process is simple (copy at the destination folder and delete email from each current location). The problem appears if you have a list of emails e.g. 4 emails inside the inbox and we process the 2nd email in inside the list then number 3 and 4 are different, they are not the emails that we thought that they would be, which will result into an error because list item number 4 it will not exist since the list moved one position down because 2 position was empty.
So the only possible solution to this problem was to use UIDs. Which are unique numbers for each email. So no matter how the email will change this number will be binded with the email.
So in the example below, I fetch the UIDs on the first step,check if folder is empty no point of processing the folder else iterate for all emails found in the folder. Next fetch each email Header. The headers will help us to fetch the Subject and compare the subject of the email with the one that we are searching. If the subject matches, then continue to copy and delete the email. Then you are done. Simple as that.
#!/usr/bin/env python
import email
import pprint
import imaplib
__author__ = 'author'
def initialization_process(user_name, user_password, folder):
imap4 = imaplib.IMAP4_SSL('imap.gmail.com') # Connects over an SSL encrypted socket
imap4.login(user_name, user_password)
imap4.list() # List of "folders" aka labels in gmail
imap4.select(folder) # Default INBOX folder alternative select('FOLDER')
return imap4
def logout_process(imap4):
imap4.close()
imap4.logout()
return
def main(user_email, user_pass, scan_folder, subject_match, destination_folder):
try:
imap4 = initialization_process(user_email, user_pass, scan_folder)
result, items = imap4.uid('search', None, "ALL") # search and return uids
dictionary = {}
if items == ['']:
dictionary[scan_folder] = 'Is Empty'
else:
for uid in items[0].split(): # Each uid is a space separated string
dictionary[uid] = {'MESSAGE BODY': None, 'BOOKING': None, 'SUBJECT': None, 'RESULT': None}
result, header = imap4.uid('fetch', uid, '(UID BODY[HEADER])')
if result != 'OK':
raise Exception('Can not retrieve "Header" from EMAIL: {}'.format(uid))
subject = email.message_from_string(header[0][1])
subject = subject['Subject']
if subject is None:
dictionary[uid]['SUBJECT'] = '(no subject)'
else:
dictionary[uid]['SUBJECT'] = subject
if subject_match in dictionary[uid]['SUBJECT']:
result, body = imap4.uid('fetch', uid, '(UID BODY[TEXT])')
if result != 'OK':
raise Exception('Can not retrieve "Body" from EMAIL: {}'.format(uid))
dictionary[uid]['MESSAGE BODY'] = body[0][1]
list_body = dictionary[uid]['MESSAGE BODY'].splitlines()
result, copy = imap4.uid('COPY', uid, destination_folder)
if result == 'OK':
dictionary[uid]['RESULT'] = 'COPIED'
result, delete = imap4.uid('STORE', uid, '+FLAGS', '(\Deleted)')
imap4.expunge()
if result == 'OK':
dictionary[uid]['RESULT'] = 'COPIED/DELETED'
elif result != 'OK':
dictionary[uid]['RESULT'] = 'ERROR'
continue
elif result != 'OK':
dictionary[uid]['RESULT'] = 'ERROR'
continue
else:
print "Do something with not matching emails"
# do something else instead of copy
dictionary = {scan_folder: dictionary}
except imaplib.IMAP4.error as e:
print("Error, {}".format(e))
except Exception as e:
print("Error, {}".format(e))
finally:
logout_process(imap4)
return dictionary
if __name__ == "__main__":
username = 'example.email#gmail.com'
password = 'examplePassword'
main_dictionary = main(username, password, 'INBOX', 'BOKNING', 'TMP_FOLDER')
pprint.pprint(main_dictionary)
exit(0)
Useful information regarding imaplib Python — imaplib IMAP example with Gmail and the imaplib documentation.
This is the solution to move multiple from one folder to another.
mail_server = 'imap.gamil.com'
account_id = 'yourimap#gmail.com'
password = 'testpasword'
TLS_port = '993'
# connection to imap
conn = imaplib.IMAP4_SSL(mail_server,TLS_port)
try:
(retcode, capabilities) = conn.login(account_id, password)
# return HttpResponse("pass")
except:
# return HttpResponse("fail")
messages.error(request, 'Request Failed! Unable to connect to Mailbox. Please try again.')
return redirect('addIEmMailboxes')
conn.select('"INBOX"')
(retcode, messagess) = conn.uid('search', None, "ALL")
if retcode == 'OK':
for num in messagess[0].split():
typ, data = conn.uid('fetch', num,'(RFC822)')
msg = email.message_from_bytes((data[0][1]))
#MOVE MESSAGE TO ProcessedEmails FOLDER
result = conn.uid('COPY', num, 'ProcessedEmails')
if result[0] == 'OK':
mov, data = conn.uid('STORE', num , '+FLAGS', '(\Deleted)')
conn.expunge()
conn.close()
return redirect('addIEmMailboxes')
Solution with Python 3, to move Zoho mails from Trash to Archive. (Zoho does not archive deleted messages, so if you want to preserve them forever, you need to move from Trash to an archival folder.)
#!/usr/bin/env python3
import imaplib, sys
obj = imaplib.IMAP4_SSL('imap.zoho.com', 993)
obj.login('account', 'password')
obj.select('Trash')
_, data = obj.uid('FETCH', '1:*' , '(RFC822.HEADER)')
if data[0] is None:
print("No messages in Trash")
sys.exit(0)
messages = [data[i][0].split()[2] for i in range(0, len(data), 2)]
for msg_uid in messages:
apply_lbl_msg = obj.uid('COPY', msg_uid, 'Archive')
if apply_lbl_msg[0] == 'OK':
mov, data = obj.uid('STORE', msg_uid , '+FLAGS', '(\Deleted)')
obj.expunge()
print("Moved msg %s" % msg_uid)
else:
print("Copy of msg %s did not work" % msg_uid)
My external lib: https://github.com/ikvk/imap_tools
# MOVE all messages from INBOX to INBOX/folder2
from imap_tools import MailBox
with MailBox('imap.ya.ru').login('tst#ya.ru', 'pwd', 'INBOX') as mailbox:
mailbox.move(mailbox.fetch('ALL'), 'INBOX/folder2') # *implicit creation of uid list on fetch