Skip to content

Commit c68373f

Browse files
committed
Initial commit
1 parent 76535ec commit c68373f

File tree

4 files changed

+498
-1
lines changed

4 files changed

+498
-1
lines changed

Diff for: AddTagToObjects.py

+134
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
import argparse
2+
import os
3+
4+
from cpapi import APIClient, APIClientArgs
5+
6+
import Utils
7+
8+
9+
def populate_parser():
10+
parser = argparse.ArgumentParser(description="Add tags to objects.")
11+
parser.add_argument("--username", "-u", required=False, default=os.getenv('MGMT_CLI_USER'),
12+
help="The management administrator's user name.\nEnvironment variable: MGMT_CLI_USER")
13+
parser.add_argument("--password", "-p", required=False,
14+
help="The management administrator's password.\nEnvironment variable: MGMT_CLI_PASSWORD")
15+
parser.add_argument("--management", "-m", required=False, default=os.getenv('MGMT_CLI_MANAGEMENT', "127.0.0.1"),
16+
help="The management server's IP address (In the case of a Multi-Domain Environment, "
17+
"use the IP address of the MDS domain).\nDefault: 127.0.0.1\nEnvironment variable: "
18+
"MGMT_CLI_MANAGEMENT")
19+
parser.add_argument("--port", "--server-port", required=False, default=os.getenv('MGMT_CLI_PORT', 443),
20+
help="The port of the management server\nDefault: 443\nEnvironment variable: MGMT_CLI_PORT")
21+
parser.add_argument("--domain", "-d", required=False, default=os.getenv('MGMT_CLI_DOMAIN'),
22+
help="The name, uid or IP-address of the management domain\n"
23+
"Environment variable: MGMT_CLI_DOMAIN")
24+
parser.add_argument('--root', '-r', choices=['true', 'false'],
25+
help='\b{%(choices)s}\nLogin as root. When running on the management server, '
26+
'use this flag with value set to \'true\' to login as Super User administrator.',
27+
metavar=" \b\b")
28+
parser.add_argument('--session-name', help='\nSession unique name. Default {add_tag}',
29+
default="add_tag", metavar="")
30+
parser.add_argument('--session-description', help='Session description. Default {Current time}',
31+
default=Utils.DATETIME_NOW_STR, metavar="")
32+
parser.add_argument('--partial-name', '-pn', required=False,
33+
help="Add tag to objects shown in object explorer by the provided partial-name. "
34+
"\nThis field required in case of using \'--only-used\' flag")
35+
parser.add_argument('--mode', '-md', default='unused', choices=['used', 'unused', 'all'],
36+
help="Use this flag with value set to \'used\' to update only used objects, "
37+
"\'unused\' to update only unused objects or \'all\' to ignore the filter." +
38+
" \nDefault: \'unused\'.")
39+
parser.add_argument('--tag', '-t', required=True, help="Name of the tag to add.")
40+
return parser.parse_args()
41+
42+
43+
def is_in_use(client, uid):
44+
res = client.api_call("where-used", {"uid": uid})
45+
Utils.exit_failure("Failed to get usages of " + uid, res, client)
46+
if int(res.data.get("used-directly").get("total")) > 0:
47+
return True
48+
else:
49+
return False
50+
51+
52+
def main():
53+
user_args = populate_parser()
54+
Utils.log_file = open(os.path.dirname(os.path.abspath(__file__)) + os.sep + 'add_tag' +
55+
(user_args.domain if user_args.domain else "") + '_' +
56+
str(Utils.DATETIME_NOW_SEC) + '.txt', 'w+')
57+
client_args = APIClientArgs(server=user_args.management, port=user_args.port)
58+
59+
with APIClient(client_args) as client:
60+
# The API client, would look for the server's certificate SHA1 fingerprint in a file.
61+
# If the fingerprint is not found on the file, it will ask the user if he accepts the server's fingerprint.
62+
# In case the user does not accept the fingerprint, exit the program.
63+
if client.check_fingerprint() is False:
64+
Utils.print_msg("Could not get the server's fingerprint - Check connectivity with the server.")
65+
exit(1)
66+
67+
Utils.login(user_args, client)
68+
69+
if user_args.partial_name:
70+
result = client.api_query(command="show-objects", payload={"in": ["name", user_args.partial_name]})
71+
objects = result.data
72+
else:
73+
if user_args.mode.lower() != "unused":
74+
print("Can not use \'--mode\' flag set to \'used\' or \'all\' without \'partial-name\'")
75+
client.api_call("discard")
76+
exit(1)
77+
result = client.api_query(command="show-unused-objects", payload={})
78+
objects = result.data
79+
pass
80+
81+
i = 0
82+
for candidate_object in objects:
83+
object_type = candidate_object.get("type")
84+
uid = candidate_object.get("uid")
85+
86+
if user_args.partial_name and user_args.mode:
87+
if user_args.mode.lower() == "used":
88+
if is_in_use(client, uid) is False:
89+
Utils.print_msg("WARNING: Object not in use " + uid)
90+
continue
91+
elif user_args.mode.lower() == "unused":
92+
if is_in_use(client, uid) is True:
93+
Utils.print_msg("WARNING: Object in use " + uid)
94+
continue
95+
96+
res = client.api_call("set-" + object_type, {"uid": uid, "tags": {"add": user_args.tag}})
97+
98+
if res.success is False:
99+
if res.error_message == "Requested API command: [set-" + object_type + "] not found":
100+
Utils.print_msg("WARNING: Object of type \'" + object_type + "\' is not supported. " +
101+
"If necessary add tag manually to \'" + candidate_object.get("name") + "\'.")
102+
print("WARNING: Object of type " + object_type + " is not supported. " +
103+
"If necessary add tag manually to " + candidate_object.get("name") + ".")
104+
continue
105+
elif "Object " + uid + " is read-only." in res.error_message:
106+
Utils.print_msg("WARNING: \'" + candidate_object.get("name") + "\' of type \'" + object_type +
107+
"\' is read only object.")
108+
print("WARNING: \'" + candidate_object.get("name") + "\' of type \'" + object_type +
109+
"\' is read only object.")
110+
continue
111+
elif "cannot be locked because it belongs to domain" in res.error_message:
112+
Utils.print_msg("WARNING: \'" + candidate_object.get("name") + "\' of type \'" + object_type +
113+
"\' is from other domain.")
114+
print("WARNING: \'" + candidate_object.get("name") + "\' of type \'" + object_type +
115+
"\' is from other domain.")
116+
continue
117+
else:
118+
Utils.exit_failure("Fail to set " + object_type + " with uid " + uid, res, client)
119+
else:
120+
Utils.print_msg("tag was added successfully to \'" + candidate_object.get("name") + "\'")
121+
print("tag was added successfully to \'" + candidate_object.get("name") + "\'")
122+
i = i + 1
123+
if i % 50 == 0:
124+
res = client.api_call("publish")
125+
Utils.exit_failure("Publish operation failed ", res, client)
126+
127+
res = client.api_call("publish")
128+
Utils.exit_failure("Publish operation failed ", res, client)
129+
Utils.print_msg("Script finished successfully")
130+
Utils.log_file.close()
131+
132+
133+
if __name__ == "__main__":
134+
main()

Diff for: README.md

+80-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,80 @@
1-
# UsefulManagementApiTools
1+
# Useful Management Api Tools
2+
Check Point Useful Management Api Tools contain scripts and tools that were used as solutions for customers.
3+
You can adjust the code according to your organization’s policy / needs.
4+
5+
- This tools can be executed on Management Server / Multi-Domain servers of version of R80.10 and up.
6+
7+
## Instructions
8+
Clone the repository with this command:
9+
```git
10+
git clone https://github.com/CheckPointSW/UsefulManagementApiTools
11+
```
12+
or by clicking the _‘Download ZIP’_ button.
13+
14+
Download and install the [Check Point API Python SDK](https://github.com/CheckPointSW/cp_mgmt_api_python_sdk)
15+
repository, follow the instructions in the SDK repository.
16+
17+
## AddTagToObjects.py
18+
Tool to add a tag to multiple objects.
19+
<br>The tool supports three modes of tagging by given partial-name:
20+
* Add tag to all objects.
21+
* Add tag to the unused objects.
22+
* Add tag to the used objects.
23+
24+
<br>If partial name is not supplied the tool will tag all unused objects.
25+
26+
#### Main Options
27+
*__More options and details can be found with the '-h' option by running:__ python AddTagToObjects.py –h*
28+
29+
* [--tag, -t]&emsp; The tag name that will be added to the objects.
30+
* [--partial-name , -pn]&emsp; Add tag to objects shown in object explorer by the provided partial-name.
31+
This field required in case of using \'--mode\' flag. The default is to add tag to all unused objects in the domain.
32+
* [--mode, -md]&emsp; Whether to consider if the objects are used or unused when adding the tag by name.
33+
<br>&emsp;&emsp;There are three modes, the default is \'unused\':<br>
34+
* unused: add tag only to unused objects with the given partial-name.
35+
* used: add tag only to used objects with the given partial-name.
36+
* all: add tag to all objects with the given partial-name.
37+
38+
#### Examples
39+
* Running the tool on a remote management server:
40+
<br>```python AddTagToObjects.py --tag TagForUnusedObjects -m 172.23.78.160 -u James -p MySecretPassword!```
41+
<br>The tool runs on a remote management server with IP address 172.23.78.160 and the tag "MyTag" will be added to all unused objects.
42+
43+
* Running the tool on a Multi-Domain Server for a specific domain:
44+
<br>```python AddTagToObjects.py -t MyTag -d local_domain -u James -p MySecretPassword!```
45+
46+
* Running the tool on a Security Management Server with partial name:
47+
<br>```python AddTagToObjects.py --tag my_host --partial-name "host_" -u James -p MySecretPassword!```
48+
<br>The tool will add "my_host" tag to all the unused objects that are found in the explorer with the given partial-name.
49+
50+
* Running the tool on a Security Management Server with partial name of unused objects:
51+
<br>```python AddTagToObjects.py --tag my_host --partial-name "host_" --mode all -u James -p MySecretPassword!```
52+
<br>The tool will add "my_host" tag to all the objects that are found in the explorer with the given partial-name.
53+
54+
55+
## ReplaceReference.py
56+
Replace references of two given objects.
57+
The tool supports replacement in Access, Threat and Nat rules, and in groups and service-groups.
58+
59+
#### Main Options
60+
*__More options and details can be found with the '-h' option by running:__ python ReplaceReference.py –h*
61+
62+
* [--original-reference, -o]&emsp; The full name of the replaced object, must be unique name.
63+
* [--new-reference, -n]&emsp; The full name of the new object, must be unique name.
64+
65+
#### Examples
66+
* Running the tool on a remote management server:
67+
<br>```python ReplaceReference.py --original-reference old_host --new-reference new_host -m 172.23.78.160 -u James -p MySecretPassword!```
68+
<br>The tool runs on a remote management server with IP address 172.23.78.160 and replaces references from old_host to new_host.
69+
70+
* Running the tool on a Multi-Domain Server for a specific domain:
71+
<br>```python ReplaceReference.py -o Global_object -n local_object -d local_domain -u James -p MySecretPassword!```
72+
<br>The tool can replace references to a Global object with references to a local object.
73+
74+
75+
## Development Environment
76+
The tool is developed using Python language version 2.7, version 3.7 and [Check Point API Python SDK](https://github.com/CheckPointSW/cp_mgmt_api_python_sdk).
77+
78+
79+
80+

0 commit comments

Comments
 (0)