Script rhn_custom_info_py
[hide private]
[frames] | no frames]

Source Code for Script script-rhn_custom_info_py

  1  #!/usr/bin/python -u 
  2  # 
  3  # Copyright (c) 2008--2016 Red Hat, Inc. 
  4  # 
  5  # This software is licensed to you under the GNU General Public License, 
  6  # version 2 (GPLv2). There is NO WARRANTY for this software, express or 
  7  # implied, including the implied warranties of MERCHANTABILITY or FITNESS 
  8  # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 
  9  # along with this software; if not, see 
 10  # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. 
 11  # 
 12  # Red Hat trademarks are not licensed under GPLv2. No permission is 
 13  # granted to use or replicate Red Hat trademarks that are incorporated 
 14  # in this software or its documentation. 
 15  # 
 16   
 17   
 18  import sys 
 19  import os 
 20  import getpass 
 21   
 22  try: 
 23      import xmlrpclib 
 24  except ImportError: 
 25      import xmlrpc.client as xmlrpclib 
 26      basestring = (str, bytes) 
 27   
 28  from re import search 
 29  from optparse import OptionParser 
 30  from rhn import rpclib 
 31   
 32  from up2date_client import config 
 33  from up2date_client import up2dateAuth 
 34   
 35   
36 -def create_server_obj(server_url):
37 38 cfg = config.initUp2dateConfig() 39 40 enable_proxy = cfg['enableProxy'] 41 proxy_host = None 42 proxy_user = None 43 proxy_password = None 44 45 if enable_proxy: 46 proxy_host = config.getProxySetting() 47 48 if cfg['enableProxyAuth']: 49 proxy_user = cfg['proxyUser'] 50 proxy_password = cfg['proxyPassword'] 51 52 ca = cfg['sslCACert'] 53 54 if isinstance(ca, basestring): 55 ca = [ca] 56 57 ca_certs = ca or ["/usr/share/rhn/RHNS-CA-CERT"] 58 59 lang = None 60 for env in 'LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG': 61 if env in os.environ: 62 lang = os.environ[env].split(':')[0] 63 lang = lang.split('.')[0] 64 break 65 else: 66 continue 67 68 69 server = rpclib.Server(server_url, 70 proxy=proxy_host, 71 username=proxy_user, 72 password=proxy_password) 73 74 if lang: 75 server.setlang(lang) 76 77 if server_url.startswith("https"): 78 for ca_cert in ca_certs: 79 if not os.access(ca_cert, os.R_OK): 80 raise "could not find cert %s" % ca_cert 81 82 server.add_trusted_cert(ca_cert) 83 84 return server
85 86
87 -def read_username():
88 tty = open("/dev/tty", "w") 89 tty.write('Username: ') 90 tty.close() 91 92 try: 93 username = sys.stdin.readline().rstrip('\n') 94 except KeyboardInterrupt: 95 print("") 96 sys.exit(0) 97 if username is None: 98 # EOF 99 print("") 100 sys.exit(0) 101 return username.strip()
102 103
104 -def system_exit(code, msgs=None):
105 "Exit with a code and optional message(s). Saved a few lines of code." 106 107 if msgs: 108 if type(msgs) not in [type([]), type(())]: 109 msgs = (msgs, ) 110 for msg in msgs: 111 sys.stderr.write(str(msg)+'\n') 112 sys.exit(code)
113 114
115 -def parse_args():
116 parser = OptionParser() 117 parser.set_usage("rhn-custom-info [options] key1 value1 key2 value2 ...") 118 parser.add_option("-u", "--username", 119 action="store", type="string", dest="username", 120 help="your RHN username", metavar="RHN_LOGIN") 121 122 parser.add_option("-p", "--password", 123 action="store", type="string", dest="password", 124 help="your RHN password", metavar="RHN_PASSWD") 125 126 parser.add_option("-s", "--server-url", 127 action="store", type="string", dest="url", 128 help="use the rhn api at URL", metavar="URL") 129 130 parser.add_option("-d", "--delete-values", 131 action="store_true", dest="delete_values", default=0, 132 help="delete one or multiple custom keys from the system") 133 134 parser.add_option("-l", "--list-values", 135 action="store_true", dest="list_values", default=0, 136 help="list the custom keys and values for the system", 137 ) 138 139 140 return parser.parse_args()
141 142
143 -def verify_command_line():
144 145 (options, args) = parse_args() 146 num_args = len(args) 147 148 if not options.username: 149 options.username = read_username() 150 151 if not options.password: 152 options.password = getpass.getpass() 153 154 if not (num_args % 2 == 0) and not options.list_values and not options.delete_values: 155 system_exit(1, "Odd number of arguments; you must provide key/value pairs") 156 157 if not args and not options.list_values and not options.delete_values: 158 system_exit(1, "You must provide key/value pairs to store") 159 160 if '' in [x.strip() for x in args]: 161 system_exit(1, "Not valid value is provided for key/value pairs") 162 163 if not args and options.delete_values: 164 system_exit(1, "You must provide a key to delete") 165 166 return (options, args, num_args)
167 168
169 -def get_sys_id():
170 sysid_xml = up2dateAuth.getSystemId() 171 172 if not sysid_xml: 173 system_exit(1, "Could not get RHN systemid") 174 175 m = search('ID-(?P<sysid>[0-9]+)', sysid_xml) 176 177 if m: 178 return m.group('sysid') 179 else: 180 return
181
182 -def munge_server_url(u2d_server_url):
183 m = search('(?P<prot_and_host>http[s]?://.*?/)XMLRPC', u2d_server_url) 184 185 if m: 186 return m.group('prot_and_host') + 'rpc/api'
187
188 -def main():
189 190 (options, args, num_args) = verify_command_line() 191 192 values = {} 193 valuesdel = [] 194 195 i = 0 196 if not options.delete_values: 197 while (i < num_args): 198 values[args[i]] = args[i+1] 199 i = i + 2 200 else: 201 while (i < num_args): 202 valuesdel.insert(i, args[i]) 203 i = i + 1 204 205 url = None 206 if options.url: 207 url = options.url 208 else: 209 url = munge_server_url(config.getServerlURL()[0]) 210 211 s = create_server_obj(url) 212 213 sid = get_sys_id() 214 215 if not sid: 216 system_exit(1, "Could not determine systemid") 217 218 try: 219 session = s.auth.login(options.username, options.password) 220 221 if options.list_values: 222 ret = s.system.get_custom_values(session, int(sid)) 223 elif options.delete_values: 224 ret = s.system.delete_custom_values(session, int(sid), valuesdel) 225 else: 226 ret = s.system.set_custom_values(session, int(sid), values) 227 228 except xmlrpclib.Fault: 229 t, e = sys.exc_info()[:2] 230 if e.faultCode == -1: 231 system_exit(1, "Error code: %s\nInvalid login information.\n" % e.faultCode) 232 else: 233 system_exit(1, "Error code: %s\n%s\n" % (e.faultCode, e.faultString)) 234 235 236 # handle list and set modes for output... 237 if options.list_values: 238 239 if not ret: 240 system_exit(0, "No custom values set for this system.\n") 241 242 for key in ret: 243 print ("%s\t%s" % (key, ret[key])) 244 245 system_exit(0, None) 246 247 else: 248 if ret: 249 system_exit(0, None); 250 else: 251 system_exit(1, "Unknown failure!\n")
252 253 if __name__ == "__main__": 254 main() 255