2 # -*- coding: utf-8 -*-
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
16 # @author: David Blaisonneau <david.blaisonneau@orange.com>
17 # @author: Arnaud Morin <arnaud1.morin@orange.com>
19 #~ from foreman.api import Api
21 from bs4 import BeautifulSoup
26 """ FreeIP return an available IP in the targeted network """
28 def __init__ (self, login, password):
29 """ Init: get authenticity token """
30 with requests.session() as self.session:
32 #~ 1/ Get login token and authentify
34 log_soup = BeautifulSoup(self.session.get('https://127.0.0.1/users/login', verify=False).text)
35 payload['utf8'] = log_soup.findAll('input',attrs={'name':'utf8'})[0].get('value')
36 payload['authenticity_token'] = log_soup.findAll('input',attrs={'name':'authenticity_token'})[0].get('value')
37 if payload['authenticity_token'] == None:
38 raise requests.exceptions.RequestException("Bad catch of authenticity_token")
39 payload['commit']='Login'
40 payload['login[login]'] = login
41 payload['login[password]'] = password
43 r = self.session.post('https://127.0.0.1/users/login', verify=False, data=payload)
44 if r.status_code != 200:
45 raise requests.exceptions.RequestException("Bad login or password")
46 #~ Get token for host creation
47 log_soup = BeautifulSoup(self.session.get('https://127.0.0.1/hosts/new', verify=False).text)
48 self.authenticity_token = log_soup.findAll('input',attrs={'name':'authenticity_token'})[0].get('value')
49 if payload['authenticity_token'] == None:
50 raise requests.exceptions.RequestException("Bad catch of authenticity_token")
51 except requests.exceptions.RequestException as e:
52 print("Error connection Foreman to get a free ip")
57 def get(self, subnet, mac = ""):
58 payload = {"host_mac": mac, "subnet_id": subnet}
59 payload['authenticity_token'] = self.authenticity_token
61 self.last_ip = json.loads(self.session.post('https://127.0.0.1/subnets/freeip', verify=False, data=payload).text)['ip']
62 if payload['authenticity_token'] == None:
63 raise requests.exceptions.RequestException("Error getting free IP")
64 except requests.exceptions.RequestException as e:
65 print("Error connection Foreman to get a free ip")
72 if __name__ == "__main__":
75 if len(sys.argv) == 4:
76 f = FreeIP(sys.argv[1], sys.argv[2])
77 print(f.get(sys.argv[3]))
79 print('Error: Usage\npython {} foreman_user foreman_password subnet'.format(sys.argv[0]))