1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293
|
# Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; version 2 of the
# License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
import platform
import os
import posixpath
import ntpath
import errno
import threading
import tempfile
import StringIO
import pipes
import subprocess
import time
import inspect
import random
import string
import functools
# Declares the global variable for sudo prefix
default_sudo_prefix = ''
def reset_sudo_prefix():
global default_sudo_prefix
default_sudo_prefix = '/usr/bin/sudo -S -p EnterPasswordHere'
reset_sudo_prefix()
from mforms import App
from workbench.utils import QueueFileMP
from wb_common import InvalidPasswordError, PermissionDeniedError, Users, sanitize_sudo_output, splitpath
from wb_admin_ssh import WbAdminSSH, ConnectionError
from wb_common import CmdOptions, CmdOutput
from workbench.log import log_info, log_warning, log_error, log_debug, log_debug2, log_debug3
from workbench.tcp_utils import CustomCommandListener
from workbench.os_utils import FileUtils, OSUtils, FunctionType
class wbaOS(object):
unknown = "unknown"
windows = "windows"
linux = "linux"
darwin = "darwin"
def __setattr__(self, name, value):
raise NotImplementedError
def quote_path(path):
if path.startswith("~/"):
# be careful to not quote shell special chars
return '~/"%s"' % path[2:]
else:
return '"%s"' % path.replace('"', r'\"')
def quote_path_win(path):
return '"%s"' % path.replace("/", "\\").replace('"', r'\"')
def wrap_for_sudo(command, sudo_prefix, as_user = Users.ADMIN, to_spawn = False):
if not command:
raise Exception("Empty command passed to execution routine")
if not sudo_prefix:
sudo_prefix = default_sudo_prefix
if to_spawn:
command += ' &'
sudo_prefix += ' /usr/bin/nohup'
# If as_user is the CURRENT then there's no need to sudo
if as_user != Users.CURRENT:
#sudo needs to use -u <user> for non admin
if as_user != Users.ADMIN:
sudo_user = "sudo -u %s" % as_user
sudo_prefix = sudo_prefix.replace('sudo', sudo_user)
if '/bin/sh' in sudo_prefix or '/bin/bash' in sudo_prefix:
command = sudo_prefix + " \"" + command.replace('\\', '\\\\').replace('"', r'\"').replace('$','\\$') + "\""
else:
command = sudo_prefix + " /bin/bash -c \"" + command.replace('\\', '\\\\').replace('"', r'\"').replace('$','\\$') + "\""
return command
###
# Function decorator for absolute path validation
def useAbsPath(param):
def abs_path_validator(function):
@functools.wraps(function)
def decorated_function(*args, **kw):
path_index = None
try:
path_index = function.__code__.co_varnames.index(param)
except ValueError:
# this implies an internal coding error and will just be logged
# It means the programmer indicated to validate an unexisting parameter
log_warning ('Error on path validation for function %s, using invalid parameter "%s"\n' % (function.__name__, param))
# Only performs the actual validation when a valid parameter is set
if path_index is not None:
path_value = args[path_index]
if type(path_value) not in [str, unicode] or not os.path.isabs(path_value):
raise ValueError('Error on path validation for function "%s", parameter "%s" must be an absolute path: %s' % (function.__name__, param, path_value))
return function(*args, **kw)
return decorated_function
return abs_path_validator
class SSH(WbAdminSSH):
def __init__(self, profile, password_delegate):
self.mtx = threading.Lock()
self.wrapped_connect(profile, password_delegate)
def __del__(self):
log_debug("Closing SSH connection\n")
self.close()
def get_contents(self, filename):
self.mtx.acquire()
try:
ret = WbAdminSSH.get_contents(self, filename)
finally:
self.mtx.release()
return ret
def set_contents(self, filename, data, mode="w"):
self.mtx.acquire()
try:
ret = WbAdminSSH.set_contents(self, filename, data, mode)
finally:
self.mtx.release()
return ret
def exec_cmd(self, cmd, as_user = Users.CURRENT, user_password = None, output_handler = None, read_size = 128, get_channel_cb = None, options = None):
output = None
retcode = None
self.mtx.acquire()
log_debug3('%s:exec_cmd(cmd="%s", sudo=%s)\n' % (self.__class__.__name__, cmd, str(as_user)) )
try:
(output, retcode) = WbAdminSSH.exec_cmd(self, cmd,
as_user=as_user,
user_password=user_password,
output_handler=output_handler,
read_size = read_size,
get_channel_cb = get_channel_cb,
options = options)
log_debug3('%s:exec_cmd(): Done cmd="%s"\n' % (self.__class__.__name__, cmd) )
finally:
self.mtx.release()
return (output, retcode)
##===================================================================================================
## Local command execution
def local_run_cmd_linux(command, as_user = Users.CURRENT, user_password=None, sudo_prefix=default_sudo_prefix, output_handler=None, output_timeout=15, options=None):
# wrap cmd
if as_user != Users.CURRENT:
command = wrap_for_sudo(command, sudo_prefix, as_user)
debug_run_cmd = False
if debug_run_cmd:
log_debug2("local_run_cmd_linux: %s (as %s)\n" % (command, as_user))
script = command.strip(" ")
if not script:
return None
script_to_log = script
script = "cd; " + script + " ; exit $?"
result = None
def read_nonblocking(fd, size, timeout=0, return_on_newline=False):
import select
data = []
t = time.time()
while len(data) < size:
try:
r, _, _ = select.select([fd], [], [], timeout)
except select.error, e:
if e.args[0] == 4:
timeout -= time.time() - t
if timeout < 0:
break
continue
raise
if not r:
break
data.append(fd.read(1))
if return_on_newline and data[-1] == "\n":
break
return "".join(data)
def read_nonblocking_until_nl_or(proc, fd, text, timeout=0):
import select
data = ""
t = time.time()
while time.time() - t < timeout:
try:
r, _, _ = select.select([fd], [], [], timeout - (time.time() - t))
except select.error, e:
if e.args[0] == 4:
continue
raise
if not r:
break
new_byte = fd.read(1)
if new_byte:
data += new_byte
if data.endswith(text) or "\n" in data:
ndata = sanitize_sudo_output(data)
if ndata != data:
data = ndata
continue
break
elif proc.poll() is not None:
break
return data
# script should already have sudo
my_env = os.environ.copy()
my_env['LANG'] = "C" # Force english locale
child = subprocess.Popen(["/bin/sh", "-c", script], bufsize=0,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
close_fds=True, env = my_env)
expect_sudo_failure = False
if as_user != Users.CURRENT:
# If sudo is being used, we need to input the password
data = read_nonblocking_until_nl_or(child, child.stdout, "EnterPasswordHere", timeout=output_timeout)
if data.endswith("EnterPasswordHere"):
if not user_password:
log_debug2("Password required for sudo, but user_password is empty, throwing exception.")
child.terminate() # sudo need pw, but pw is empty, throw exception,
# it will be handled upper in the chain and proper pw dialog will be shown.
raise InvalidPasswordError("Incorrect password for sudo")
# feed the password
if debug_run_cmd:
log_debug2("local_run_cmd_linux: sending password to child...\n")
child.stdin.write((user_password or " ")+"\n"+'\x1a')
expect_sudo_failure = True # we could get a Sorry or the password prompt again
else:
# If the prompt didn't come in, it could mean that password is not required
# or it could also mean that sudo printed some junk/banner message before sending over the prompt
# Problem is, there's no way to tell whether the text coming in is the output from the program being executed
# or stuff from sudo itself, until either the sudo finishes or the prompt is seen.
# So to account for this case, we will buffer everything that comes until:
# - until the sudo prompt is seen
# - a certain number of lines are read from the pipe
# - until a timeout occurs (a short one, since the banner shouldn't take very long to get printed)
# - until the sudo terminates
log_debug2("sudo prompt available, but it's not standard. Trying to parse.")
max_lines_to_read_until_giving_up_waiting_for_sudo_prompt = 10
num_seconds_to_wait_for_sudo_greeting_message_until_we_assume_prompt_wont_come = 1
buffered_output = [data] # init with the data that came in initially
start_time = time.time()
while child.poll() is None:
data = read_nonblocking_until_nl_or(child, child.stdout, "EnterPasswordHere", timeout=1)
if data.endswith("EnterPasswordHere"):
if not user_password:
log_debug2("Password required for sudo, but user_password is empty, throwing exception.")
child.terminate() # sudo need pw, but pw is empty, throw exception,
# it will be handled upper in the chain and proper pw dialog will be shown.
raise InvalidPasswordError("Incorrect password for sudo")
log_info("Banner message from sudo for command %s:\n%s\n" % (script, "".join(buffered_output)))
buffered_output = None
# ok, so the stuff that came in until now is all garbage and the sudo prompt finally arrived
if debug_run_cmd:
log_debug2("local_run_cmd_linux: sending password to child, after receiving greeting from sudo...\n")
child.stdin.write((user_password or "")+"\n")
expect_sudo_failure = True # we could get a Sorry or the password prompt again
break
else:
buffered_output.append(data)
if len(buffered_output) > max_lines_to_read_until_giving_up_waiting_for_sudo_prompt or \
time.time() - start_time < num_seconds_to_wait_for_sudo_greeting_message_until_we_assume_prompt_wont_come:
log_debug("local_run_cmd_linux: was expecting sudo password prompt, but it never came\n")
# ok, we assume the output that came in until now is all from the program and there's no sudo prompt
break
if output_handler and buffered_output:
for line in buffered_output:
output_handler(line)
if debug_run_cmd:
log_debug2("local_run_cmd_linux: waiting for data...\n")
read_size = 40
return_on_newline = True
while child.poll() is None:
#t = time.time()
# read 1KB from stdout, timeout in 15s.. at first time, read just enough to see if password prompt is there again
current_text = read_nonblocking(child.stdout, read_size, output_timeout, return_on_newline)
return_on_newline = False
read_size = 1024
if debug_run_cmd:
log_debug2("local_run_cmd_linux: %s: read %i bytes from child [%s...]\n" % (script_to_log, len(current_text), current_text[:50]))
# If Password prompt shows up again, it means the password we tried earlier was wrong.. so raise an exception
if expect_sudo_failure and (current_text.find("EnterPasswordHere") >= 0 or current_text.find("Sorry, try again") >= 0):
child.terminate()
raise InvalidPasswordError("Incorrect password for sudo")
else:
# Not the password prompt
expect_sudo_failure = False
if output_handler and current_text:
output_handler(current_text)
# Try to read anything left, wait exit
try:
current_text, _ = child.communicate()
if current_text and output_handler:
output_handler(current_text)
except:
pass
result = child.returncode
if debug_run_cmd:
log_debug2("local_run_cmd_linux: child returned %s\n" % result)
log_debug3('local_run_cmd_linux(): script="%s", ret=%s\n' % (script_to_log, result))
return result
def local_run_cmd_windows(command, as_user=Users.CURRENT, user_password=None, sudo_prefix=None, output_handler=None, options=None):
# wrap cmd
retcode = 1
if as_user != Users.CURRENT:
# Starts the command execution listener
listener = None
# When the command output is needed, the command will be executed with the
# helper script and the output listened on a socket connection
if output_handler:
# The TCPCommandListener is missing one thing: the way to turn it off
# so can't be used yet
#listener = TCPCommandListener(output_handler)
listener = CustomCommandListener(output_handler)
listener.start()
helper_path = ntpath.join(os.getcwd(),App.get().get_resource_path("wbadminhelper.exe"))
# Creates the command as a call to the bundled python
# - The path to the python helper which will receive additionally:
# - The port where the command listener is waiting for the helper response
# - The handshake to allow it to connect to the listener
# - The close_key so it can notify the listener when processing is done
# - The original command to be executed
# Patch to ensure old OS calls get executed properly
actual_command = command.split(' ')[0]
if not actual_command in ['LISTDIR','GETFILE','GET_FREE_SPACE', 'CHECK_FILE_READABLE', 'CHECK_DIR_WRITABLE', 'CHECK_PATH_EXISTS', 'CREATE_DIRECTORY', 'CREATE_DIRECTORY_RECURSIVE', 'REMOVE_DIRECTORY', 'REMOVE_DIRECTORY_RECURSIVE','DELETE_FILE', 'COPY_FILE', 'GET_FILE_OWNER', 'GETFILE_LINES', 'EXEC']:
command = "EXEC " + command
cmdname = helper_path
cmdparams = '%d %s %s %s' % (listener.port, listener.handshake, listener.close_key, command)
else:
cmdname = "cmd.exe"
cmdparams = "/C" + command
command = "%s %s" % (cmdname, cmdparams)
try:
from ctypes import c_int, WINFUNCTYPE, windll
from ctypes.wintypes import HWND, LPCSTR, UINT
prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, LPCSTR, LPCSTR, UINT)
paramflags = (1, "hwnd", 0), (1, "operation", "runas"), (1, "file", cmdname), (1, "params", cmdparams), (1, "dir", None), (1, "showcmd", 0)
SHellExecute = prototype(("ShellExecuteA", windll.shell32), paramflags)
ret = SHellExecute()
# If the user chooses to not allow privilege elevation for the operation
# a PermissionDeniedError is launched
if ret == 5:
raise PermissionDeniedError("User did not accept privilege elevation")
# Waits till everything has been received from the command
if listener and ret != 5:
listener.join()
if listener.exit_status:
try:
helper_exception = eval(listener.exit_message)
except Exception, e:
# Some networking exceptions can't be evaluated
# So a runtime exception will be created on those cases
helper_exception = RuntimeError(listener.exit_message)
log_error("Exception received from Windows command helper executing %s %s: %s\n" % (cmdname, cmdparams, helper_exception))
raise helper_exception
# > 32 is OK, < 32 is error code
retcode = 1
if ret > 32:
retcode = 0
else:
if ret == 0:
log_error('local_run_cmd_windows(): Out of memory executing "%s"\n' % command)
else:
log_error('local_run_cmd_windows(): Error %i executing "%s"\n' % (ret, command) )
return retcode
except Exception, e:
# These errors will contain information probably sent by the helper so
# they will be rethrow so they get properly displayed
raise
else:
try:
retcode = OSUtils.exec_command(command, output_handler)
except Exception, e:
import traceback
log_error("Exception executing local command: %s: %s\n%s\n" % (command, e, traceback.format_exc()))
retcode = 1
#out_str = "Internal error: %s" % e
return retcode
if platform.system() == "Windows":
local_run_cmd = local_run_cmd_windows
else:
local_run_cmd = local_run_cmd_linux
def local_get_cmd_output(command, as_user=Users.CURRENT, user_password=None):
output = []
output_handler = lambda line, l=output: l.append(line)
rc = local_run_cmd(command=command, as_user=as_user, user_password=user_password, sudo_prefix=None, output_handler=output_handler)
return ("\n".join(output), rc)
##===================================================================================================
## Process Execution
_process_ops_classes = []
class ProcessOpsBase(object):
cmd_output_encoding = ""
def __init__(self, **kwargs):
pass
def post_init(self):
pass
def expand_path_variables(self, path):
return path
def get_cmd_output(self, command, as_user=Users.CURRENT, user_password=None):
output = []
output_handler = lambda line, l=output: l.append(line)
rc = self.exec_cmd(command, as_user, user_password, output_handler)
return ("\n".join(output), rc)
def list2cmdline(self, args):
return None
class ProcessOpsNope(ProcessOpsBase):
@classmethod
def match(cls, (host, target, connect)):
return connect == 'none'
def expand_path_variables(self, path):
return path
def exec_cmd(self, command, as_user=Users.CURRENT, user_password=None, output_handler=None, options=None):
return None
def spawn_process(self, command, as_user=Users.CURRENT, user_password=None, output_handler=None, options=None):
raise NotImplementedError("%s must implement spawn_process" % self.__class__.__name__)
def get_cmd_output(self, command, as_user=Users.CURRENT, user_password=None):
return ("", None)
_process_ops_classes.append(ProcessOpsNope)
class ProcessOpsLinuxLocal(ProcessOpsBase):
@classmethod
def match(cls, (host, target, connect)):
return connect == 'local' and (host in (wbaOS.linux, wbaOS.darwin) and target in (wbaOS.linux, wbaOS.darwin))
def __init__(self, **kwargs):
ProcessOpsBase.__init__(self, **kwargs)
self.sudo_prefix= kwargs.get("sudo_prefix", default_sudo_prefix)
def exec_cmd(self, command, as_user=Users.CURRENT, user_password=None, output_handler=None, options = None):
return local_run_cmd_linux(command, as_user, user_password, self.sudo_prefix, output_handler, 15, options)
def spawn_process(self, command, as_user=Users.CURRENT, user_password=None, output_handler=None, options=None):
sudo_prefix = self.sudo_prefix
if options and options.has_key(CmdOptions.CMD_HOME):
sudo_prefix = "%s HOME=%s" % (sudo_prefix, options[CmdOptions.CMD_HOME])
# wrap cmd
if as_user != Users.CURRENT:
command = wrap_for_sudo(command, sudo_prefix, as_user, True)
script = command.strip(" ")
if script is None or len(script) == 0:
return None
# Creates the process
process = subprocess.Popen(script, stdin=subprocess.PIPE, shell=True, close_fds=True)
# Passes the password if needed
if as_user != Users.CURRENT:
process.stdin.write(user_password + "\n")
process.stdin.flush()
return 0
def list2cmdline(self, args):
return " ".join([pipes.quote(a) or "''" for a in args])
_process_ops_classes.append(ProcessOpsLinuxLocal)
class ProcessOpsLinuxRemote(ProcessOpsBase):
@classmethod
def match(cls, (host, target, connect)):
# host doesn't matter
return connect == 'ssh' and target in (wbaOS.linux, wbaOS.darwin)
def __init__(self, **kwargs): # Here should be at least commented list of args
ProcessOpsBase.__init__(self, **kwargs)
self.sudo_prefix= kwargs.get("sudo_prefix", default_sudo_prefix)
self.ssh = kwargs["ssh"]
def exec_cmd(self, command, as_user=Users.CURRENT, user_password=None, output_handler=None, options=None):
#if not self.ssh:
# raise Exception("No SSH session active")
if as_user != Users.CURRENT:
command = wrap_for_sudo(command, self.sudo_prefix, as_user)
def ssh_output_handler(chunk, handler):
if "EnterPasswordHere" in chunk and as_user != Users.CURRENT:
raise InvalidPasswordError("Invalid password for sudo")
if chunk is not None and chunk != "":
handler(chunk)
if output_handler:
handler = lambda chunk, h=output_handler: ssh_output_handler(chunk, h)
else:
handler = None
if self.ssh:
# output_handler taken by ssh.exec_cmd is different from the one used elsewhere
dummy_text, ret = self.ssh.exec_cmd(command,
as_user=as_user, user_password=user_password,
output_handler=handler, options=options)
else:
ret = 1
if output_handler:
output_handler("No SSH connection is active")
else:
print("No SSH connection is active")
log_info('No SSH connection is active\n')
return ret
def spawn_process(self, command, as_user=Users.CURRENT, user_password=None, output_handler=None, options=None):
if as_user != Users.CURRENT:
# options has been introduced to allow customizing the HOME folder for the
# user spawning the process.
# This is required to prevent nohup raising a Permission Denied error trying
# to write the nohup.out on a non writable folder
sudo_prefix = self.sudo_prefix
if options and options.has_key(CmdOptions.CMD_HOME):
sudo_prefix = "%s HOME=%s" % (sudo_prefix, options[CmdOptions.CMD_HOME])
command = wrap_for_sudo(command, sudo_prefix, as_user, True)
def ssh_output_handler(chunk, handler):
if "EnterPasswordHere" in chunk and as_user != Users.CURRENT:
raise InvalidPasswordError("Invalid password for sudo")
if chunk is not None and chunk != "":
handler(chunk)
if output_handler:
handler = lambda chunk, h=output_handler: ssh_output_handler(chunk, h)
else:
handler = None
if self.ssh:
# output_handler taken by ssh.exec_cmd is different from the one used elsewhere
dummy_text, ret = self.ssh.exec_cmd(command,
as_user=as_user, user_password=user_password,
output_handler=handler, options = options)
else:
ret = 1
if output_handler:
output_handler("No SSH connection is active")
else:
print("No SSH connection is active")
log_info('No SSH connection is active\n')
return ret
def list2cmdline(self, args):
return " ".join([pipes.quote(a) or "''" for a in args])
_process_ops_classes.append(ProcessOpsLinuxRemote)
WIN_REG_QUERY_PROGRAMFILES = 'reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion /v "ProgramFilesDir"'
WIN_REG_QUERY_PROGRAMFILES_x86 = 'reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion /v "ProgramFilesDir (x86)"'
WIN_PROGRAM_FILES_VAR = "%ProgramFiles%"
WIN_PROGRAM_FILES_X86_VAR = "%ProgramFiles(x86)%"
WIN_PROGRAM_FILES_X64_VAR = "%ProgramW6432%"
WIN_PROGRAM_DATA_VAR = "%ProgramData%"
class ProcessOpsWindowsLocal(ProcessOpsBase):
@classmethod
def match(cls, (host, target, connect)):
return (host == wbaOS.windows and target == wbaOS.windows and connect in ('wmi', 'local'))
def __init__(self, **kwargs):
ProcessOpsBase.__init__(self, **kwargs)
self.target_shell_variables = {}
def post_init(self):
self.fetch_windows_shell_info()
def exec_cmd(self, command, as_user, user_password, output_handler=None, options = None):
return local_run_cmd_windows(command, as_user, user_password, None, output_handler, options)
def spawn_process(self, command, as_user=Users.CURRENT, user_password=None, output_handler=None, options=None):
try:
DETACHED_PROCESS = 0x00000008
subprocess.Popen(command, shell=True, close_fds = True, creationflags=DETACHED_PROCESS)
#process = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell=True)
except Exception, exc:
import traceback
log_error("Error executing local Windows command: %s: %s\n%s\n" % (command, exc, traceback.format_exc()))
#out_str = "Internal error: %s"%exc
def expand_path_variables(self, path):
"""
Expand some special variables in the path, such as %ProgramFiles% and %ProgramFiles(x86)% in
Windows. Uses self.target_shell_variables for the substitutions, which should have been
filled when the ssh connection to the remote host was made.
"""
for k, v in self.target_shell_variables.iteritems():
path = path.replace(k, v)
return path
def fetch_windows_shell_info(self):
# get some info from the remote shell
result, code = self.get_cmd_output("chcp.com")
if code == 0:
result = result.strip(" .\r\n").split()
if len(result) > 0:
self.cmd_output_encoding = "cp" + result[-1]
else:
log_warning('%s.fetch_windows_shell_info(): WARNING: Unable to determine codepage from shell: "%s"\n' % (self.__class__.__name__, str(result)) )
# some ppl don't have the system32 dir in PATH for whatever reason, check if that's the case
_, code = self.get_cmd_output("ver")
if code != 0:
# assume this is not Windows
raise RuntimeError("Target host is configured as Windows, but seems to be a different OS. Please review the connection settings.")
raise RuntimeError("Unable to execute command chcp. Please make sure that the C:\\Windows\\System32 directory is in your PATH environment variable.")
result, code = self.get_cmd_output("echo %PROCESSOR_ARCHITECTURE%")
if result:
result = result.strip()
ProgramFilesVar = None
x86var = None
if result != "x86":#we are on x64 win in x64 mode
x86var = WIN_PROGRAM_FILES_X86_VAR
ProgramFilesVar = WIN_PROGRAM_FILES_VAR
else:
result, code = self.get_cmd_output("echo %PROCESSOR_ARCHITEW6432%")
if result:
result = result.strip()
if result == "%PROCESSOR_ARCHITEW6432%":#we are on win 32
x86var = WIN_PROGRAM_FILES_VAR
ProgramFilesVar = WIN_PROGRAM_FILES_VAR
else:#32bit app on x64 win
x86var = WIN_PROGRAM_FILES_VAR
ProgramFilesVar = WIN_PROGRAM_FILES_X64_VAR
result, code = self.get_cmd_output("echo "+ ProgramFilesVar)
if code == 0:
self.target_shell_variables["%ProgramFiles%"] = result.strip("\r\n")
if ProgramFilesVar != "%ProgramFiles%":
self.target_shell_variables[ProgramFilesVar] = result.strip("\r\n")
else:
print "WARNING: Unable to fetch ProgramFiles value in Windows machine: %s"%result
log_warning('%s.fetch_windows_shell_info(): WARNING: Unable to fetch ProgramFiles value in Windows machine: "%s"\n' % (self.__class__.__name__, str(result)) )
# this one only exists in 64bit windows
result, code = self.get_cmd_output("echo "+ x86var)
if code == 0:
self.target_shell_variables["%ProgramFiles(x86)%"] = result.strip("\r\n")
else:
print "WARNING: Unable to fetch ProgramFiles(x86) value in local Windows machine: %s"%result
log_warning('%s.fetch_windows_shell_info(): WARNING: Unable to fetch ProgramFiles(x86) value in local Windows machine: "%s"\n' % (self.__class__.__name__, str(result)) )
# Fetches the ProgramData path
result, code = self.get_cmd_output("echo "+ WIN_PROGRAM_DATA_VAR)
if code == 0:
self.target_shell_variables[WIN_PROGRAM_DATA_VAR] = result.strip("\r\n")
else:
# If not found, it will use the %ProgramFiles% variable value
self.target_shell_variables[WIN_PROGRAM_DATA_VAR] = self.target_shell_variables[ProgramFilesVar]
print "WARNING: Unable to fetch ProgramData value in local Windows machine: %s, using ProgramFiles path instead: %s" % (result, self.target_shell_variables[WIN_PROGRAM_DATA_VAR])
log_warning('%s.fetch_windows_shell_info(): WARNING: Unable to fetch ProgramData value in local Windows machine: "%s"\n' % (self.__class__.__name__, str(result)) )
log_debug('%s.fetch_windows_shell_info(): Encoding: "%s", Shell Variables: "%s"\n' % (self.__class__.__name__, self.cmd_output_encoding, str(self.target_shell_variables)))
def list2cmdline(self, args):
return subprocess.list2cmdline(args)
_process_ops_classes.append(ProcessOpsWindowsLocal)
class ProcessOpsWindowsRemoteSSH(ProcessOpsWindowsLocal):
@classmethod
def match(cls, (host, target, connect)):
# host doesn't matter
return (target == wbaOS.windows and connect == 'ssh')
def __init__(self, **kwargs):
ProcessOpsWindowsLocal.__init__(self, **kwargs)
self.ssh = kwargs["ssh"]
def post_init(self):
if self.ssh:
self.fetch_windows_shell_info()
def exec_cmd(self, command, as_user=Users.CURRENT, user_password=None, output_handler=None, options=None):
command = "cmd.exe /c " + command
if not self.ssh:
raise Exception("No SSH session active")
def ssh_output_handler(chunk, handler):
if chunk is not None and chunk != "":
handler(chunk)
#else:
# loop = False
if output_handler:
handler = lambda chunk, h=output_handler: ssh_output_handler(chunk, h)
else:
handler = None
# output_handler taken by ssh.exec_cmd is different from the one used elsewhere
dummy_text, ret = self.ssh.exec_cmd(command,
as_user=as_user, user_password=user_password,
output_handler=handler, options=options)
return ret
def spawn_process(self, command, as_user=Users.CURRENT, user_password=None, output_handler=None, options=None):
raise NotImplementedError("%s must implement spawn_process" % self.__class__.__name__)
def list2cmdline(self, args):
return subprocess.list2cmdline(args)
_process_ops_classes.append(ProcessOpsWindowsRemoteSSH)
##===================================================================================================
## File Operations
_file_ops_classes = []
class FileOpsNope(object):
@classmethod
def match(cls, target_os, connection_method):
return connection_method == "none"
def __init__(self, process_ops, ssh = None, target_os = None):
pass
def save_file_content(self, filename, content, as_user = Users.CURRENT, user_password = None, mode = None):
pass
def save_file_content_and_backup(self, filename, content, backup_extension, as_user = Users.CURRENT, user_password = None, mode = None):
pass
def get_file_content(self, filename, as_user = Users.CURRENT, user_password = None, skip_lines=0):
return ""
def _copy_file(self, source, dest, as_user = Users.CURRENT, user_password = None): # not used externally
pass
def check_file_readable(self, path, as_user=Users.CURRENT, user_password=None):
return False
def check_dir_writable(self, path, as_user=Users.CURRENT, user_password=None):
return False
def file_exists(self, path, as_user = Users.CURRENT, user_password = None):
return False
def get_file_owner(self, path, as_user = Users.CURRENT, user_password = None):
return False
def create_directory(self, path, as_user = Users.CURRENT, user_password = None, with_owner=None):
pass
def create_directory_recursive(self, path, as_user = Users.CURRENT, user_password = None, with_owner=None):
pass
def get_available_space(self, path, as_user = Users.CURRENT, user_password = None):
return False
# Return format is list of entries in dir (directories go first, each dir name is follwoed by /)
def listdir(self, path, as_user = Users.CURRENT, user_password = None, include_size=False): # base operation to build file_exists and remote file selector
return []
def get_owner(self, path): # base operation to build file_exists and remote file selector
return []
def join_paths(self, path, *paths):
pass
_file_ops_classes.append(FileOpsNope)
class FileOpsLinuxBase(object):
def __init__(self, process_ops, ssh=None, target_os = None):
self.process_ops = process_ops
self.ssh = ssh
self.target_os = target_os
# Exception Handling will vary on local and remote
def raise_exception(self, message, custom_messages = {}):
raise Exception(message)
@useAbsPath("filename")
def file_exists(self, filename, as_user=Users.CURRENT, user_password=None):
res = self.process_ops.exec_cmd('test -e ' + quote_path(filename),
as_user,
user_password,
output_handler = lambda line:None,
options={CmdOptions.CMD_WAIT_OUTPUT:CmdOutput.WAIT_NEVER})
return res == 0
@useAbsPath("path")
def get_available_space(self, path, as_user=Users.CURRENT, user_password=None):
output = StringIO.StringIO()
res = self.process_ops.exec_cmd("LC_ALL=C df -Ph %s" % quote_path(path),
as_user,
user_password,
output_handler = output.write)
output = sanitize_sudo_output(output.getvalue()).strip()
available = "Could not determine"
if res == 0:
tokens = output.split("\n")[-1].strip().split()
available = "%s of %s available" % (tokens[3], tokens[1])
return available
@useAbsPath("path")
def get_file_owner(self, path, as_user = Users.CURRENT, user_password = None):
if self.target_os == wbaOS.linux:
command = 'LC_ALL=C stat -c %U '
else:
command = 'LC_ALL=C /usr/bin/stat -f "%Su" '
output = StringIO.StringIO()
command = command + quote_path(path)
res = self.process_ops.exec_cmd(command,
as_user,
user_password,
output_handler= output.write)
output = sanitize_sudo_output(output.getvalue()).strip()
if res != 0:
self.raise_exception(output)
return output
@useAbsPath("path")
def create_directory(self, path, as_user = Users.CURRENT, user_password = None, with_owner=None):
output = StringIO.StringIO()
if with_owner:
# Chown is usually restricted to the root user
if as_user == Users.CURRENT:
raise PermissionDeniedError("Cannot set owner of directory %s" % path)
else:
command = "/bin/mkdir %s && chown %s %s" % (quote_path(path), with_owner, quote_path(path))
else:
command = "/bin/mkdir %s" % (quote_path(path))
res = self.process_ops.exec_cmd(command,
as_user = as_user,
user_password = user_password,
output_handler = output.write,
options={CmdOptions.CMD_WAIT_OUTPUT:CmdOutput.WAIT_IF_FAIL})
if res != 0:
output = sanitize_sudo_output(output.getvalue()).strip()
self.raise_exception(output)
@useAbsPath("path")
def create_directory_recursive(self, path, as_user = Users.CURRENT, user_password = None, with_owner=None):
head, tail = splitpath(path)
if not tail:
head, tail = splitpath(head)
if head and tail and not self.file_exists(head):
try:
self.create_directory_recursive(head, as_user, user_password, with_owner)
except OSError, e:
if e.errno != errno.EEXIST:
raise
self.create_directory(path, as_user, user_password, with_owner)
@useAbsPath("path")
def remove_directory(self, path, as_user = Users.CURRENT, user_password = None):
output = StringIO.StringIO()
res = self.process_ops.exec_cmd('/bin/rmdir ' + quote_path(path),
as_user = as_user,
user_password = user_password,
output_handler = output.write,
options={CmdOptions.CMD_WAIT_OUTPUT:CmdOutput.WAIT_IF_FAIL})
if res != 0:
output = sanitize_sudo_output(output.getvalue()).strip()
self.raise_exception(output)
@useAbsPath("path")
def remove_directory_recursive(self, path, as_user = Users.CURRENT, user_password = None):
output = StringIO.StringIO()
res = self.process_ops.exec_cmd('/bin/rm -R ' + quote_path(path),
as_user = as_user,
user_password = user_password,
output_handler = output.write,
options={CmdOptions.CMD_WAIT_OUTPUT:CmdOutput.WAIT_IF_FAIL})
if res != 0:
output = sanitize_sudo_output(output.getvalue()).strip()
self.raise_exception(output)
@useAbsPath("path")
def delete_file(self, path, as_user = Users.CURRENT, user_password = None):
output = StringIO.StringIO()
res = self.process_ops.exec_cmd("/bin/rm " + quote_path(path),
as_user = as_user,
user_password = user_password,
output_handler = output.write,
options = {CmdOptions.CMD_WAIT_OUTPUT:CmdOutput.WAIT_IF_FAIL})
if res != 0:
output = sanitize_sudo_output(output.getvalue()).strip()
self.raise_exception(output)
@useAbsPath("filename")
def get_file_content(self, filename, as_user = Users.CURRENT, user_password = None, skip_lines=0): # may raise IOError
command = ''
output = StringIO.StringIO()
if skip_lines == 0:
command = 'LC_ALL=C cat %s' % quote_path(filename)
else:
command = 'LC_ALL=C tail -n+%d %s' % (skip_lines+1, quote_path(filename))
res = self.process_ops.exec_cmd(command,
as_user = as_user,
user_password = user_password,
output_handler = output.write)
output = sanitize_sudo_output(output.getvalue()).strip()
if res != 0:
self.raise_exception(output)
return output
@useAbsPath("path")
def _create_file(self, path, content):
try:
f = open(path, 'w')
f.write(content)
f.close()
except (IOError, OSError), err:
if err.errno == errno.EACCES:
raise PermissionDeniedError("Could not open file %s for writing" % path)
raise err
def _copy_file(self, source, dest, as_user = Users.CURRENT, user_password = None):
output = StringIO.StringIO()
res = self.process_ops.exec_cmd("LC_ALL=C /bin/cp " + quote_path(source) + " " + quote_path(dest),
as_user = as_user,
user_password = user_password,
output_handler = output.write,
options = {CmdOptions.CMD_WAIT_OUTPUT:CmdOutput.WAIT_IF_FAIL})
if res != 0:
output = sanitize_sudo_output(output.getvalue()).strip()
self.raise_exception(output)
@useAbsPath("path")
def check_file_readable(self, path, as_user=Users.CURRENT, user_password=None):
ret_val = True
output = StringIO.StringIO()
path = quote_path(path)
command = "test -e %s;_fe=$?;test -f %s;_fd=$?;test -r %s;echo $_fe$_fd$?" % (path, path, path)
self.process_ops.exec_cmd(command,
as_user,
user_password,
output_handler = output.write)
# The validation will depend on the output and not the returned value
output = sanitize_sudo_output(output.getvalue()).strip()
log_debug2('check_file_readable :%s %s\n' % (len(output), output))
if len(output) == 3:
if output[0] == '1':
raise OSError(errno.ENOENT, 'The path "%s" does not exist' % path)
elif output[1] == '1':
raise OSError(errno.ENOTDIR, 'The path "%s" is not a regular file' % path)
elif output[2] == '1':
ret_val = False
else:
raise Exception('Unable to verify file is readable : %s' % output)
return ret_val
@useAbsPath("path")
def check_dir_writable(self, path, as_user=Users.CURRENT, user_password=None):
ret_val = True
output = StringIO.StringIO()
path = quote_path(path)
command = "test -e %s;_fe=$?;test -d %s;_fd=$?;test -w %s;echo $_fe$_fd$?" % (path, path, path)
self.process_ops.exec_cmd(command,
as_user,
user_password,
output_handler = output.write)
# The validation will depend on the output and not the returned value
output = sanitize_sudo_output(output.getvalue()).strip()
log_debug('check_dir_writable :%s %s\n' % (len(output), output))
if len(output) == 3:
if output[0] == '1':
raise OSError(errno.ENOENT, 'The path "%s" does not exist' % path)
elif output[1] == '1':
raise OSError(errno.ENOTDIR, 'The path "%s" is not a directory' % path)
elif output[2] == '1':
ret_val = False
else:
raise Exception('Unable to verify directory is writable : %s' % output)
return ret_val
@useAbsPath("path")
def listdir(self, path, as_user = Users.CURRENT, user_password = None, include_size=False):
file_list = []
if include_size:
# for ls -l, the output format changes depending on stdout being a terminal or not
# since both cases are possible, we need to handle both at the same time (1st line being total <nnnn> or not)
# the good news is that if the line is there, then it will always start with total, regardless of the locale
command = 'LC_ALL=C /bin/ls -l -p %s' % quote_path(path)
else:
command = 'LC_ALL=C /bin/ls -1 -p %s' % quote_path(path)
output = StringIO.StringIO()
res = self.process_ops.exec_cmd(command,
as_user,
user_password,
output_handler = output.write)
output = sanitize_sudo_output(output.getvalue().strip())
if res != 0:
custom_messages = {
errno.ENOENT:"The path \"%s\" does not exist" % path,
errno.ENOTDIR:"The path \"%s\" is not a directory" % path,
errno.EACCES:"Permission denied accessing %s" % path
}
self.raise_exception(output, custom_messages)
else:
try:
if include_size:
file_list = [(f, int(s)) for _, _, _, _, s, _, _, _, f in [s.strip().split(None, 8) for s in output.split("\n") if not s.startswith('total')]]
else:
file_list = [s.strip() for s in output.split("\n")]
except Exception, e:
log_error("%s: Could not parse output of remote ls %s command: '%s'\n"% (e, path, output))
return file_list
def save_file_content(self, filename, content, as_user = Users.CURRENT, user_password = None, mode = None):
pass
def _set_file_content(self, path, content):
pass
def _create_temp_file(self, content):
tmp = tempfile.NamedTemporaryFile(delete = False)
tmp_name = tmp.name
try:
log_debug('%s: Writing file contents to tmp file "%s"\n' % (self.__class__.__name__, tmp_name) )
tmp.write(content)
tmp.flush()
except Exception, exc:
log_error('%s: Exception caught: %s\n' % (self.__class__.__name__, str(exc)) )
if tmp:
tmp.close()
raise
return tmp_name
@useAbsPath("filename")
def save_file_content_and_backup(self, filename, content, backup_extension, as_user = Users.CURRENT, user_password = None, mode = None):
log_debug('%s: Saving file "%s" with backup (sudo="%s")\n' % (self.__class__.__name__, filename, str(as_user)) )
# Checks if the target folder is writable
target_dir = posixpath.split(filename)[0]
if self.check_dir_writable(target_dir, as_user, user_password):
# Creates a backup of the existing file... if any
if backup_extension and self.file_exists(filename, as_user, user_password):
log_debug('%s: Creating backup of "%s" to "%s"\n' % (self.__class__.__name__, filename, filename+backup_extension))
self._copy_file(source = filename, dest = filename + backup_extension,
as_user = as_user, user_password = user_password)
if as_user != Users.CURRENT:
temp_file = self._create_temp_file(content)
log_debug('%s: Wrote file contents to tmp file "%s"\n' % (self.__class__.__name__, temp_file) )
log_debug('%s: Copying over tmp file to final filename using sudo: %s -> %s\n' % (self.__class__.__name__, temp_file, filename) )
self._copy_file(source = temp_file, dest = filename,
as_user = Users.ADMIN, user_password = user_password)
log_debug('%s: Copying file done\n' % self.__class__.__name__)
# If needed changes the ownership of the new file to the requested user
if as_user != Users.ADMIN:
# TODO: Does this need any validation being executed by root??
self.process_ops.exec_cmd("chown %s %s" % (as_user, quote_path(filename)),
as_user = Users.ADMIN,
user_password = user_password,
output_handler = None,
options = {CmdOptions.CMD_WAIT_OUTPUT:CmdOutput.WAIT_IF_FAIL})
self.delete_file(temp_file)
else:
log_debug('%s: Saving file...\n' % self.__class__.__name__)
self._create_file(filename, content)
if mode:
self.process_ops.exec_cmd("chmod %s %s" % (mode, quote_path(filename)),
as_user = Users.ADMIN,
user_password = user_password,
output_handler = None,
options = {CmdOptions.CMD_WAIT_OUTPUT:CmdOutput.WAIT_IF_FAIL})
else:
raise PermissionDeniedError("Cannot write to target folder: %s" % target_dir)
def join_paths(self, path, *paths):
result = posixpath.join(path, *paths)
log_error("Remote join paths [FileOpsLinuxBase]: %s\n" % result)
return result
#===============================================================================
# The local file ops are context free, meaning that they
# do not need active shell session to work on
# local all plain
# save_file_content - python
# get_file_content - python
# copy_file - python
# get_dir_access - python (returns either rw or ro or none)
# listdir - python
# local all sudo derives from local-all-plain
# save_file_content - shell
# get_file_content - python (maybe sudo if file is 0600)
# copy_file - shell
# get_dir_access - python (returns either rw or ro or none)
# listdir - python/shell(for ro-dirs)
class FileOpsLocalUnix(FileOpsLinuxBase):
@classmethod
def match(cls, target_os, connection_method):
return connection_method == "local" and target_os in (wbaOS.linux, wbaOS.darwin)
process_ops = None
def __init__(self, process_ops, ssh=None, target_os = None):
FileOpsLinuxBase.__init__(self, process_ops, ssh, target_os)
# Still need to differentiate whether it is an OSError or an IOError
def raise_exception(self, message, custom_messages = {}):
for code, name in errno.errorcode.iteritems():
if os.strerror(code) in message:
if code == errno.EACCES:
raise PermissionDeniedError(custom_messages.get(code, message))
raise OSError(code, custom_messages.get(code, message))
raise Exception(custom_messages.get(None, message))
# content must be a string
@useAbsPath("filename")
def save_file_content(self, filename, content, as_user = Users.CURRENT, user_password = None, mode = None):
self.save_file_content_and_backup(filename, content, None, as_user, user_password, mode)
# UseCase: If get_file_content fails with exception of access, try sudo
@useAbsPath("filename")
def get_file_content(self, filename, as_user = Users.CURRENT, user_password = None, skip_lines=0):
if as_user == Users.CURRENT:
try:
f = open(filename, 'r')
except (IOError, OSError), e:
if e.errno == errno.EACCES:
raise PermissionDeniedError("Can't open file '%s'" % filename)
raise e
if skip_lines > 0:
#unused last_skipped_line = ""
skipped = 0
lines = []
for line in f:
if skipped < skip_lines:
#unused last_skipped_line = "%d - %s\n" % (skipped, line)
pass
else:
lines.append(line.rstrip())
skipped = skipped + 1
cont = "\n".join(lines)
else:
cont = f.read()
f.close()
else:
cont = FileOpsLinuxBase.get_file_content(self, filename, as_user, user_password, skip_lines)
return cont
@useAbsPath("path")
def delete_file(self, path, as_user = Users.CURRENT, user_password = None):
if as_user == Users.CURRENT:
FileUtils.delete_file(path)
else:
FileOpsLinuxBase.delete_file(self, path, as_user, user_password)
def _copy_file(self, source, dest, as_user = Users.CURRENT, user_password = None):
if as_user == Users.CURRENT:
FileUtils.copy_file(source, dest)
else:
FileOpsLinuxBase._copy_file(self, source, dest, as_user, user_password)
# Return format is list of entries in dir (directories go first, each dir name is followed by /)
@useAbsPath("path")
def listdir(self, path, as_user = Users.CURRENT, user_password = None, include_size=False): # base operation to build file_exists and remote file selector
file_list = []
if as_user == Users.CURRENT:
FileUtils.list_dir(path, include_size, lambda l, list = file_list: file_list.append(l))
if include_size:
file_list = [(f, int(s)) for s, f in [s.strip().split(" ", 1) for s in file_list]]
else:
file_list = [s.strip() for s in file_list]
else:
file_list = FileOpsLinuxBase.listdir(self, path, as_user, user_password, include_size)
return file_list
def join_paths(self, path, *paths):
result = posixpath.join(path, *paths)
log_error("Remote join paths [FileOpsLocalUnix]: %s\n" % result)
return result
_file_ops_classes.append(FileOpsLocalUnix)
#===============================================================================
class FileOpsLocalWindows(object): # Used for remote as well, if not using sftp
@classmethod
def match(cls, target_os, connection_method):
return connection_method in ("local", "wmi") and target_os == wbaOS.windows
def __init__(self, process_ops, ssh=None, target_os = None):
self.process_ops = process_ops
self.ssh = ssh
self.target_os = target_os
tempdir, rc= self.process_ops.get_cmd_output("echo %temp%")
if tempdir and tempdir.strip():
self.tempdir = tempdir.strip()
def exec_helper_command(self, command, result_mode, as_user, user_password):
"""
This function is in charge of executing a command through the admin helper
and processes the result depending on the result_mode parameter
It was created to avoid having a result parsing on each function called
through the admin helper and simplify code
"""
ret_val = None
out = []
res = self.process_ops.exec_cmd(command,
as_user,
user_password,
output_handler = lambda line, l = out:l.append(line))
if res == 0:
if result_mode == FunctionType.Boolean:
# Only booleans are expected, if an error
# occurred it has been already raised on an exception
if out[0] == 'True':
ret_val = True
elif out[0] == 'False':
ret_val = False
elif result_mode == FunctionType.Success:
# nothing to do, is expected to succeed, if an error
# happened, it has been already raised on an exception
pass
elif result_mode == FunctionType.String:
ret_val = out[0]
elif result_mode == FunctionType.Data:
ret_val = out
else:
raise Exception('Error executing helper command : %s' % command)
return ret_val
def get_file_owner(self, path, as_user = Users.CURRENT, user_password = None):
if as_user == Users.CURRENT:
ret_val = FileUtils.get_file_owner(path)
else:
ret_val = self.exec_helper_command('GET_FILE_OWNER %s' % path, FunctionType.String, as_user, user_password)
return ret_val
def check_file_readable(self, path, as_user=Users.CURRENT, user_password=None):
if as_user == Users.CURRENT:
ret_val = FileUtils.check_file_readable(path)
else:
ret_val = self.exec_helper_command('CHECK_FILE_READABLE %s' % path, FunctionType.Boolean, as_user, user_password)
return ret_val
def check_dir_writable(self, path, as_user=Users.CURRENT, user_password=None):
if as_user == Users.CURRENT:
ret_val = FileUtils.check_dir_writable(path)
else:
ret_val = self.exec_helper_command('CHECK_DIR_WRITABLE %s' % path, FunctionType.Boolean, as_user, user_password)
return ret_val
def file_exists(self, filename, as_user = Users.CURRENT, user_password=None):
if as_user == Users.CURRENT:
ret_val = FileUtils.check_path_exists(filename)
else:
ret_val = self.exec_helper_command('CHECK_PATH_EXISTS %s' % filename, FunctionType.Boolean, as_user, user_password)
return ret_val
def get_available_space(self, path, as_user=Users.CURRENT, user_password=None):
if as_user == Users.CURRENT:
ret_val = FileUtils.get_free_space(path)
else:
try:
ret_val = self.exec_helper_command('GET_FREE_SPACE %s' % path, FunctionType.String, as_user, user_password)
except Exception:
ret_val = 'Could not determine'
return ret_val
# content must be a string
def save_file_content(self, filename, content, as_user = Users.CURRENT, user_password = None, mode = None):
self.save_file_content_and_backup(filename, content, None, as_user, user_password, mode)
def save_file_content_and_backup(self, filename, content, backup_extension, as_user = Users.CURRENT, user_password = None, mode = None):
log_debug('%s: Saving file "%s" with backup (sudo="%s")\n' % (self.__class__.__name__, filename, str(as_user)) )
# First saves the content to a temporary file
try:
tmp = tempfile.NamedTemporaryFile("w+b", delete = False)
tmp_name = tmp.name
log_debug('%s: Writing file contents to tmp file "%s" as %s\n' % (self.__class__.__name__, tmp_name, as_user) )
tmp.write(content)
tmp.close()
backup_file = ""
if backup_extension and ntpath.exists(filename):
backup_file = filename + backup_extension
if as_user != Users.CURRENT:
if backup_file:
copy_command = 'COPY_FILE %s>%s>%s' % (tmp_name, filename, backup_file)
else:
copy_command = 'COPY_FILE %s>%s' % (tmp_name, filename)
self.exec_helper_command(copy_command, FunctionType.Success, as_user, user_password)
else:
FileUtils.copy_file(tmp_name, filename, backup_file)
except Exception, exc:
log_error('%s: Exception caught: %s\n' % (self.__class__.__name__, str(exc)) )
raise
# UseCase: If get_file_content fails with exception of access, try sudo
def get_file_content(self, filename, as_user = Users.CURRENT, user_password = None, skip_lines=0):
lines = []
if as_user == Users.CURRENT:
FileUtils.get_file_lines(filename, skip_lines, lambda l, list = lines: list.append(l))
else:
lines = self.exec_helper_command('GETFILE_LINES %d %s' % (skip_lines, filename), FunctionType.Data, as_user, user_password)
return ''.join(lines)
def _copy_file(self, source, dest, as_user = Users.CURRENT, user_password = None): # not used externally, but in superclass
if as_user == Users.CURRENT:
error = FileUtils.copy_file(source, dest)
if error:
raise Exception(error)
else:
self.exec_helper_command('COPY_FILE %s>%s' % (source, dest), FunctionType.Success, as_user, user_password)
def create_directory(self, path, as_user = Users.CURRENT, user_password = None, with_owner=None):
if with_owner is not None:
raise PermissionDeniedError("Changing owner of directory not supported in Windows" % path)
if as_user == Users.CURRENT:
FileUtils.create_directory(path)
else:
self.exec_helper_command('CREATE_DIRECTORY %s' % path, FunctionType.Success, as_user, user_password)
def create_directory_recursive(self, path, as_user = Users.CURRENT, user_password = None, with_owner=None):
if with_owner is not None:
raise PermissionDeniedError("Changing owner of directory not supported in Windows" % path)
if as_user == Users.CURRENT:
FileUtils.create_directory_recursive(path)
else:
self.exec_helper_command('CREATE_DIRECTORY_RECURSIVE %s' % path, FunctionType.Success, as_user, user_password)
def remove_directory(self, path, as_user = Users.CURRENT, user_password = None):
if as_user == Users.CURRENT:
FileUtils.remove_directory(path)
else:
self.exec_helper_command('REMOVE_DIRECTORY %s' % path, FunctionType.Success, as_user, user_password)
def remove_directory_recursive(self, path, as_user = Users.CURRENT, user_password = None):
if as_user == Users.CURRENT:
FileUtils.remove_directory_recursive(path)
else:
self.exec_helper_command('REMOVE_DIRECTORY_RECURSIVE %s' % path, FunctionType.Success, as_user, user_password)
def delete_file(self, path, as_user = Users.CURRENT, user_password = None):
if as_user == Users.CURRENT:
FileUtils.delete_file(path)
else:
self.exec_helper_command('DELETE_FILE %s' % path, FunctionType.Success, as_user, user_password)
def listdir(self, path, as_user = Users.CURRENT, user_password = None, include_size=False):
file_list = []
if as_user == Users.CURRENT:
FileUtils.list_dir(path, include_size, lambda l, list = file_list: file_list.append(l))
else:
file_list = self.exec_helper_command('LISTDIR %s %s' % ("1" if include_size else "0", path), FunctionType.Data, as_user, user_password)
if include_size:
file_list = [(f, int(s)) for s, f in [s.strip().split(" ", 1) for s in file_list]]
else:
file_list = [s.strip() for s in file_list]
return file_list
def join_paths(self, path, *paths):
result = ntpath.join(path, *paths)
log_error("Remote join paths [FileOpsLocalWindows]: %s\n" % result)
return result
_file_ops_classes.append(FileOpsLocalWindows)
#===============================================================================
# This remote file ops are shell dependent, they must be
# given active ssh connection, possibly, as argument
# remote unix sudo/non-sudo
# save_file_content - shell
# get_file_content - shell
# copy_file - shell
# get_dir_access - shell(returns either rw or ro or none)
# listdir - shell(for ro-dirs)
class FileOpsRemoteUnix(FileOpsLinuxBase):
@classmethod
def match(cls, target_os, connection_method):
return connection_method == "ssh" and target_os in (wbaOS.linux, wbaOS.darwin)
def __init__(self, process_ops, ssh, target_os = None):
FileOpsLinuxBase.__init__(self, process_ops, ssh, target_os)
# Still need to differentiate whether it is an OSError or an IOError
def raise_exception(self, message, custom_messages = {}):
if 'Permission denied' in message:
raise PermissionDeniedError(custom_messages.get(errno.EACCES, message))
elif 'No such file or directory' in message:
raise OSError(errno.ENOENT, custom_messages.get(errno.ENOENT, message))
elif 'Not a directory' in message:
raise OSError(errno.ENOTDIR, custom_messages.get(errno.ENOTDIR, message))
elif 'Directory not empty' in message:
raise OSError(errno.ENOTEMPTY, custom_messages.get(errno.ENOTEMPTY, message))
elif 'No SSH connection is active' in message:
stack = inspect.stack()
if len(stack) > 1:
function = stack[1][3]
message = "Unable to perform function %s. %s" % (function, message)
raise Exception(message)
else:
raise Exception(custom_messages.get(None, message))
def create_directory(self, path, as_user = Users.CURRENT, user_password = None, with_owner=None):
if as_user == Users.CURRENT:
if with_owner is not None:
raise PermissionDeniedError("Cannot set owner of directory %s" % path)
try:
self.ssh.mkdir(path)
except (IOError, OSError), err:
if err.errno == errno.EACCES:
raise PermissionDeniedError("Could not create directory %s" % path)
raise err
else:
FileOpsLinuxBase.create_directory(self, path, as_user, user_password, with_owner)
def delete_file(self, path, as_user = Users.CURRENT, user_password = None):
if as_user == Users.CURRENT:
try:
self.ssh.remove(path)
except (IOError, OSError), err:
if err.errno == errno.EACCES:
raise PermissionDeniedError("Could not delete file %s" % path)
raise err
else:
FileOpsLinuxBase.delete_file(self, path, as_user, user_password)
#-----------------------------------------------------------------------------
def save_file_content(self, filename, content, as_user = Users.CURRENT, user_password = None, mode = None):
self.save_file_content_and_backup(filename, content, None, as_user, user_password, mode)
#-----------------------------------------------------------------------------
def _create_file(self, path, content):
try:
self.ssh.set_contents(path, content)
except (IOError, OSError), err:
if err.errno == errno.EACCES:
raise PermissionDeniedError("Could not open file %s for writing" % path)
raise err
def _create_temp_file(self, content):
tmpfilename = ''
if self.ssh is not None:
done = False
attempts = 0
while not done:
tmpfilename = '/tmp/' + ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(16))
try:
# This uses file open mode as wx to make sure the temporary has been created
# on this open attempt to avoid writing to an existing file.
self.ssh.set_contents(tmpfilename, content, "wx")
log_debug2('Created temp file: "%s".\n' % tmpfilename)
done = True
except IOError, exc:
# This is the only hting reported on a failure due to an attempt to
# create a file that already exists
if exc.message == "Failure":
log_warning('WARNING: Unable to create temp file: "%s", trying a different name.\n' % tmpfilename)
if attempts < 10:
attempts += 1
else:
log_warning('ERROR: Unable to create temp file max number of attempts reached.\n')
raise IOError('Unable to create temp file max number of attempts reached.')
else:
log_warning('ERROR: Unable to create temp file: "%s" : %s.\n' % (tmpfilename, exc))
raise exc
except Exception, exc:
log_warning('ERROR: Unable to create temp file: "%s" : %s.\n' % (tmpfilename, exc))
raise exc
else:
raise Exception("No SSH session active, cannot save file remotely")
return tmpfilename
def join_paths(self, path, *paths):
result = posixpath.join(path, *paths)
log_error("Remote join paths [FileOpsRemoteUnix]: %s\n" % result)
return result
_file_ops_classes.append(FileOpsRemoteUnix)
#===============================================================================
# remote win sudo/non-sudo
# save_file_content - sftp
# get_file_content - sftp
# copy_file - sftp
# get_dir_access - sftp(returns either rw or ro or none)
# listdir - sftp(for ro-dirs)
class FileOpsRemoteWindows(object):
@classmethod
def match(cls, target_os, connection_method):
return connection_method == "ssh" and target_os == wbaOS.windows
def __init__(self, process_ops, ssh, target_os):
self.process_ops = process_ops
self.ssh = ssh
def file_exists(self, filename, as_user=Users.CURRENT, user_password=None):
if self.ssh:
try:
return self.ssh.file_exists(filename)
except IOError:
raise
else:
print "Attempt to read remote file with no ssh session"
log_error('%s: Attempt to read remote file with no ssh session\n' % self.__class__.__name__)
raise Exception("Cannot read remote file without an SSH session")
return False
def get_available_space(self, path, as_user=Users.CURRENT, user_password=None):
out = []
res = self.process_ops.exec_cmd('dir %s' % quote_path(path),
as_user,
user_password,
output_handler = lambda line, l = out:l.append(line))
available = "Could not determine"
if res == 0 and len(out):
measures = ['B', 'KB', 'MB', 'GB', 'TB']
tokens = out[0].strip().split("\n")[-1].strip().split()
total = float(tokens[2].replace(",",""))
index = 0
while index < len(measures) and total > 1024:
total = float(total / 1024)
index = index + 1
available = "%.2f %s available" % (total, measures[index])
return available
def create_directory(self, path, as_user = Users.CURRENT, user_password = None, with_owner=None):
if with_owner is not None:
raise PermissionDeniedError("Changing owner of directory not supported in Windows" % path)
if as_user == Users.CURRENT:
try:
self.ssh.mkdir(path)
except OSError, err:
if err.errno == errno.EACCES:
raise PermissionDeniedError("Could not create directory %s" % path)
raise err
else:
command = wrap_for_sudo('mkdir ' + quote_path_win(path), self.process_ops.sudo_prefix, as_user)
out, ret = self.ssh.exec_cmd(command, as_user, user_password)
if ret != 0:
raise RuntimeError(out)
def create_directory_recursive(self, path, as_user = Users.CURRENT, user_password = None, with_owner=None):
head, tail = splitpath(path)
if not tail:
head, tail = splitpath(head)
if head and tail and not self.file_exists(head):
try:
self.create_directory_recursive(head, as_user, user_password, with_owner)
except OSError, e:
if e.errno != errno.EEXIST:
raise
self.create_directory(path, as_user, user_password, with_owner)
def remove_directory(self, path, as_user = Users.CURRENT, user_password = None):
if as_user == Users.CURRENT:
try:
self.ssh.rmdir(path)
except OSError, err:
if err.errno == errno.EACCES:
raise PermissionDeniedError("Could not remove directory %s" % path)
raise err
else:
command = wrap_for_sudo('rmdir ' + quote_path_win(path), self.process_ops.sudo_prefix, as_user)
out, ret = self.ssh.exec_cmd(command, as_user, user_password)
if ret != 0:
raise RuntimeError(out)
def remove_directory_recursive(self, path, as_user = Users.CURRENT, user_password = None):
command = wrap_for_sudo('rmdir %s /s /q' % quote_path_win(path), self.process_ops.sudo_prefix, as_user)
out, ret = self.ssh.exec_cmd(command, as_user, user_password)
if ret != 0:
raise RuntimeError(out)
def delete_file(self, path, as_user = Users.CURRENT, user_password = None):
if as_user == Users.CURRENT:
try:
self.ssh.remove(path)
except OSError, err:
if err.errno == errno.EACCES:
raise PermissionDeniedError("Could not delete file %s" % path)
raise err
else:
command = wrap_for_sudo('del ' + quote_path_win(path), self.process_ops.sudo_prefix, as_user)
out, ret = self.ssh.exec_cmd(command, as_user, user_password)
if ret != 0:
raise RuntimeError(out)
def save_file_content_and_backup(self, path, content, backup_extension, as_user = Users.CURRENT, user_password = None, mode = None):
# Check if dir, where config file will be stored is writable
dirname, filename = ntpath.split(path)
if as_user == Users.CURRENT:
if not self.check_dir_writable(dirname.strip(" \r\t\n")):
raise PermissionDeniedError("Cannot write to directory %s" % dirname)
if self.ssh is not None:
## Get temp dir for using as tmpdir
tmpdir, status = self.process_ops.get_cmd_output("echo %temp%")
if type(tmpdir) is unicode:
tmpdir = tmpdir.encode("utf8")
if type(tmpdir) is str:
tmpdir = tmpdir.strip(" \r\t\n")
if tmpdir[1] == ":":
tmpdir = tmpdir[2:]
else:
log_debug('%s: Temp directory path "%s" is not in expected form. The expected form is something like "C:\\Windows\\Temp"\n' % (self.__class__.__name__, tmpdir) )
tmpdir = None
log_debug2('%s: Got temp dir: "%s"\n' % (self.__class__.__name__, tmpdir) )
else:
tmpdir = None
if not tmpdir:
tmpdir = dirname
tmpfilename = tmpdir + r"\workbench-temp-file.ini"
log_debug('%s: Remotely writing contents to temporary file "%s"\n' % (self.__class__.__name__, tmpfilename) )
log_debug3('%s: %s\n' % (self.__class__.__name__, content) )
self.ssh.set_contents(tmpfilename, content)
if backup_extension:
log_debug('%s: Backing up "%s"\n' % (self.__class__.__name__, path) )
backup_cmd = "copy /y " + quote_path_win(path) + " " + quote_path_win(path+backup_extension)
msg, code = self.process_ops.get_cmd_output(backup_cmd)
if code != 0:
print backup_cmd, "->", msg
log_error('%s: Error backing up file: %s\n' % (self.__class__.__name__, backup_cmd+'->'+msg) )
raise RuntimeError("Error backing up file: %s" % msg)
copy_to_dest = "copy /y " + quote_path_win(tmpfilename) + " " + quote_path_win(path)
delete_tmp = "del " + quote_path_win(tmpfilename)
log_debug('%s: Copying file to final destination: "%s"\n' % (self.__class__.__name__, copy_to_dest) )
msg, code = self.process_ops.get_cmd_output(copy_to_dest)
if code != 0:
print copy_to_dest, "->", msg
log_error('%s: Error copying temporary file over destination file: %s\n%s to %s\n' % (self.__class__.__name__, msg, tmpfilename, path) )
raise RuntimeError("Error copying temporary file over destination file: %s\n%s to %s" % (msg, tmpfilename, path))
log_debug('%s: Deleting tmp file: "%s"\n' % (self.__class__.__name__, delete_tmp) )
msg, code = self.process_ops.get_cmd_output(delete_tmp)
if code != 0:
print "Could not delete temporary file %s: %s" % (tmpfilename, msg)
log_info('%s: Could not delete temporary file "%s": %s\n' % (self.__class__.__name__, tmpfilename, msg) )
else:
raise Exception("No SSH session active, cannot save file remotely")
# UseCase: If get_file_content fails with exception of access, try sudo
def get_file_content(self, filename, as_user = Users.CURRENT, user_password = None, skip_lines=0):
if self.ssh:
# Supposedly in Windows, sshd account has admin privileges, so Users.ADMIN can be ignored
try:
return self.ssh.get_contents(filename)
except IOError, exc:
if exc.errno == errno.EACCES:
raise PermissionDeniedError("Permission denied attempting to read file %s" % filename)
else:
print "Attempt to read remote file with no ssh session"
raise Exception("Cannot read remote file without an SSH session")
#TODO fix for windows
def check_file_readable(self, path, as_user=Users.CURRENT, user_password=None):
msg, code = self.process_ops.get_cmd_output('if exist ' + quote_path(path) + ' ( type '+ quote_path(path) +'>NUL && echo 0 ) else ( echo 1 )')
ret = (code == 0)
return ret
def check_dir_writable(self, path, as_user=Users.CURRENT, user_password=None):
msg, code = self.process_ops.get_cmd_output('echo 1 > ' + quote_path(path + "/wba_tmp_file.bak"))
ret = (code == 0)
if ret:
msg, code = self.process_ops.get_cmd_output('del ' + quote_path(path + "/wba_tmp_file.bak"))
return ret
def listdir(self, path, as_user = Users.CURRENT, user_password = None, include_size=False): # base operation to build file_exists and remote file selector
# TODO: user elevation
sftp = self.ssh.getftp()
(dirs, files) = sftp.ls(path, include_size=include_size)
ret = []
for d in dirs:
ret.append((d[0] + "/", d[1]) if include_size else d + "/")
return ret + list(files)
def join_paths(self, path, *paths):
result = os.path.join(path, *paths)
log_error("Remote join paths [FileOpsRemoteWindows]: %s\n" % result)
return result
_file_ops_classes.append(FileOpsRemoteWindows)
#===============================================================================
#
#===============================================================================
class ServerManagementHelper(object):
def __init__(self, profile, ssh):
settings = profile.get_settings_object()
serverInfo = settings.serverInfo
# Resets the sudo prefix accordingly
reset_sudo_prefix()
if serverInfo.has_key('sys.mysqld.sudo_override'):
sudo_override = serverInfo['sys.mysqld.sudo_override']
if sudo_override.strip():
global default_sudo_prefix
default_sudo_prefix = sudo_override
log_warning('Overriding default sudo prefix to : %s\n' % default_sudo_prefix)
self.tmp_files = [] # TODO: make sure the files will be deleted on exit
self.profile = profile
klass = None
match_tuple = (profile.host_os, profile.target_os, profile.connect_method)
for k in _process_ops_classes:
if k.match(match_tuple):
klass = k
break
if klass:
sudo_prefix=profile.sudo_prefix
if not sudo_prefix:
sudo_prefix = default_sudo_prefix
self.shell = klass(sudo_prefix=sudo_prefix, ssh=ssh)
self.shell.post_init()
else:
raise Exception("Unsupported administration target type: %s"%str(match_tuple))
klass = None
for k in _file_ops_classes:
if k.match(profile.target_os, profile.connect_method):
klass = k
break
if klass:
self.file = klass(self.shell, ssh=ssh, target_os = profile.target_os)
else:
raise Exception("Unsupported administration target type: %s:%s" % (str(profile.target_os), str(profile.connect_method)))
@property
def cmd_output_encoding(self):
if self.shell:
return self.shell.cmd_output_encoding
return ""
#-----------------------------------------------------------------------------
def check_file_readable(self, path, as_user=Users.CURRENT, user_password=None):
return self.file.check_file_readable(path, as_user, user_password)
#-----------------------------------------------------------------------------
def check_dir_writable(self, path, as_user=Users.CURRENT, user_password=None):
return self.file.check_dir_writable(path, as_user, user_password)
#-----------------------------------------------------------------------------
def file_exists(self, path, as_user = Users.CURRENT, user_password=None):
return self.file.file_exists(path, as_user, user_password)
#-----------------------------------------------------------------------------
def get_available_space(self, path, as_user = Users.CURRENT, user_password=None):
return self.file.get_available_space(path, as_user, user_password)
#-----------------------------------------------------------------------------
def get_file_owner(self, path, as_user = Users.CURRENT, user_password=None):
return self.file.get_file_owner(path, as_user, user_password)
#-----------------------------------------------------------------------------
def create_directory(self, path, as_user = Users.CURRENT, user_password=None, with_owner=None):
return self.file.create_directory(path, as_user, user_password, with_owner)
#-----------------------------------------------------------------------------
def create_directory_recursive(self, path, as_user = Users.CURRENT, user_password=None, with_owner=None):
return self.file.create_directory_recursive(path, as_user, user_password, with_owner)
#-----------------------------------------------------------------------------
def remove_directory(self, path, as_user = Users.CURRENT, user_password=None):
return self.file.remove_directory(path, as_user, user_password)
#-----------------------------------------------------------------------------
def remove_directory_recursive(self, path, as_user = Users.CURRENT, user_password=None):
return self.file.remove_directory_recursive(path, as_user, user_password)
#-----------------------------------------------------------------------------
def delete_file(self, path, as_user = Users.CURRENT, user_password=None):
return self.file.delete_file(path, as_user, user_password)
#-----------------------------------------------------------------------------
# Make sure that file is readable only by user!
def make_local_tmpfile(self):
# Here we create that file name blah-blah-blah
# if total_success:
# self.tmp_files.append(filename)
raise NotImplementedError
#-----------------------------------------------------------------------------
def get_file_content(self, path, as_user = Users.CURRENT, user_password = None, skip_lines=0):
return self.file.get_file_content(path, as_user=as_user, user_password=user_password, skip_lines=skip_lines)
#-----------------------------------------------------------------------------
def set_file_content(self, path, contents, as_user = Users.CURRENT, user_password = None, mode = None):
return self.file.save_file_content(path, contents, as_user=as_user, user_password=user_password, mode = mode)
#-----------------------------------------------------------------------------
def listdir(self, path, as_user = Users.CURRENT, user_password = None, include_size=False):
return self.file.listdir(path, as_user, user_password, include_size=include_size)
#-----------------------------------------------------------------------------
def set_file_content_and_backup(self, path, contents, backup_extension, as_user = Users.CURRENT, user_password = None, mode = None):
if type(contents) is unicode:
contents = contents.encode("utf8")
return self.file.save_file_content_and_backup(path, contents, backup_extension, as_user=as_user, user_password=user_password, mode = mode)
#-----------------------------------------------------------------------------
# Returns Status Code
# Text Output is given to output_handler, if there is any
def execute_command(self, command, as_user = Users.CURRENT, user_password=None, output_handler=None, options=None):
return self.shell.exec_cmd(command, as_user, user_password, output_handler, options)
def spawn_process(self, command, as_user=Users.CURRENT, user_password=None, output_handler=None, options=None):
return self.shell.spawn_process(command, as_user, user_password, output_handler, options)
def list2cmdline(self, args):
return self.shell.list2cmdline(args)
def join_paths(self, path, *paths):
result = self.file.join_paths(path, *paths)
log_error("Remote join paths: %s\n" % result)
return result
#===============================================================================
class LocalInputFile(object):
def __init__(self, path):
self.path = path
self._f = open(path)
def tell(self):
return self._f.tell()
@property
def size(self):
return os.stat(self.path).st_size
def get_range(self, start, end):
self._f.seek(start)
return self._f.read(end-start)
def start_read_from(self, offset):
self._f.seek(offset)
def read(self, count):
return self._f.read(count)
def readline(self):
return self._f.readline()
class SFTPInputFile(object):
def __init__(self, ctrl_be, path):
self.ctrl_be = ctrl_be
self.ssh = WbAdminSSH()
self.path = path
while True:
try: # Repeat get password while password is misspelled. Re-raise other exceptions
self.ssh.wrapped_connect(self.ctrl_be.server_profile, self.ctrl_be.password_handler)
except ConnectionError, error:
if not str(error).startswith('Could not establish SSH connection: Authentication failed'):
raise
else:
break
if not self.ssh.is_connected():
raise RuntimeError('Could not connect to remote server')
self.sftp = self.ssh.client.open_sftp()
try:
self._f = self.sftp.open(path)
except IOError:
raise RuntimeError('Could not read file %s in remote server. Please verify path and permissions' % path)
def tell(self):
return self._f.tell()
@property
def size(self):
return self.sftp.stat(self.path).st_size
def get_range(self, start, end):
self._f.seek(start)
return self._f.read(end-start)
def start_read_from(self, offset):
self._f.seek(offset)
def read(self, count):
return self._f.read(count)
def readline(self):
return self._f.readline()
import multiprocessing
class SudoTailInputFile(object):
def __init__(self, server_helper, path, password = None, password_cb = None):
self.path = path
self.server_helper = server_helper # ServerManagementHelper
self.data = None
self._password = password
self._password_cb = password_cb
self.skip_first_newline = True
self._pos = 0
self._proc = None
self._queue = None
# multiprocessing + paramiko doesn't work, so fallback to threading for remote access
self._is_local = self.server_helper.profile.is_local
# check if we can read the file as normall user, if not we need to gather password if callback is provided
self._need_sudo = False
while True:
if not self._need_sudo:
try:
if not self.server_helper.check_file_readable(self.path):
self._need_sudo = True
break
except OSError, e:
log_debug3("check_file_readable returned OSError, we will try with sudo then")
self._need_sudo = True
else:
self._password = self.get_password
self.server_helper.check_file_readable(self.path, as_user = Users.ADMIN, user_password=self._password)
break
def __del__(self):
if self._proc:
self._proc.join()
def tell(self):
return self._pos
@property
def get_password(self):
return self._password if not self._password_cb else self._password_cb()
@property
def size(self):
if not self._need_sudo:
files = self.server_helper.listdir(self.path, as_user = Users.CURRENT, user_password=None, include_size=True)
else:
files = self.server_helper.listdir(self.path, as_user = Users.ADMIN, user_password=self._password, include_size=True)
if not files:
raise RuntimeError("Could not get size of file %s" % self.path)
return files[0][1]
def get_range(self, start, end):
f = StringIO.StringIO()
if not self._need_sudo:
ret = self.server_helper.execute_command("/bin/dd if=%s ibs=1 skip=%i count=%i 2> /dev/null" % (quote_path(self.path), start, end-start), as_user = Users.CURRENT, user_password=None, output_handler=f.write)
else:
ret = self.server_helper.execute_command("/bin/dd if=%s ibs=1 skip=%i count=%i 2> /dev/null" % (quote_path(self.path), start, end-start), as_user = Users.ADMIN, user_password=self.get_password, output_handler=f.write)
if ret != 0:
raise RuntimeError("Could not get data from file %s" % self.path)
return f.getvalue()
def read_task(self, offset, file):
if not self._need_sudo:
self.server_helper.execute_command("/bin/dd if=%s ibs=1 skip=%i 2> /dev/null" % (quote_path(self.path), offset), as_user = Users.CURRENT, user_password=None, output_handler=file.write)
else:
self.server_helper.execute_command("/bin/dd if=%s ibs=1 skip=%i 2> /dev/null" % (quote_path(self.path), offset), as_user = Users.ADMIN, user_password=self.get_password, output_handler=file.write)
# this will signal the reader end that there's no more data
file.close()
def start_read_task_from(self, offset):
self._pos = offset
self._queue = multiprocessing.Queue()
self.data = QueueFileMP(self._queue)
self._proc = multiprocessing.Process(target=self.read_task, args=(offset, self.data))
import sys
# restore original stdout file descriptors before forking
stdo, stde, stdi = sys.stdout, sys.stderr, sys.stdin
sys.stdout, sys.stderr, sys.stdin = sys.real_stdout, sys.real_stderr, sys.real_stdin
self._proc.start()
sys.stdout, sys.stderr, sys.stdin = stdo, stde, stdi
if self.skip_first_newline:
# for some reason (in Mac OS X) the output is prefixed with a newline, which breaks the XML parsing.. so check for that and skip it if its the case
if self.data.peek(1) == '\n':
self.data.read(1)
def start_read_from(self, offset):
if self._is_local:
return self.start_read_task_from(offset)
self._pos = offset
f = StringIO.StringIO()
if not self._need_sudo:
self.server_helper.execute_command("/bin/dd if=%s ibs=1 skip=%i 2> /dev/null" % (quote_path(self.path), offset), as_user = Users.CURRENT, user_password=None, output_handler=f.write)
else:
self.server_helper.execute_command("/bin/dd if=%s ibs=1 skip=%i 2> /dev/null" % (quote_path(self.path), offset), as_user = Users.ADMIN, user_password=self._password, output_handler=f.write)
self.data = f
self.data.seek(0)
if self.skip_first_newline:
# for some reason (in Mac OS X) the output is prefixed with a newline, which breaks the XML parsing.. so check for that and skip it if its the case
if self.data.read(1) != '\n':
self.data.seek(0)
def read(self, count=None):
assert self.data is not None
d = self.data.read(count)
self._pos += len(d)
return d
def readline(self):
assert self.data is not None
d = self.data.readline()
self._pos += len(d)
return d
# Previous class but for windows
class AdminTailInputFile(object):
"""
This class is the windows like implementation for the tail as admin command
It is aided with a command in the admin helper which has the next syntax
GETFILE <offset> <size> <filename>
<offset> : position of the file where the read starts
<size> : number of bytes to be read, 0 indicates the rest of the file from the <offset> position
"""
def __init__(self, server_helper, path, password):
self.path = path
self.server_helper = server_helper # ServerManagementHelper
self.data = None
self._password = password
self._pos = 0
self._proc = None
self._queue = None
def __del__(self):
if self._proc:
self._proc.join()
def tell(self):
return self._pos
@property
def size(self):
files = self.server_helper.listdir(self.path, as_user = Users.ADMIN, user_password=self._password, include_size=True)
if not files:
raise RuntimeError("Could not get size of file %s" % self.path)
return files[0][1]
def get_range(self, start, end):
f = StringIO.StringIO()
ret = self.server_helper.execute_command("GETFILE %i %i file=%s" % (start, end-start, quote_path(self.path)), as_user = Users.ADMIN, user_password=self._password, output_handler=f.write)
if ret != 0:
raise RuntimeError("Could not get data from file %s" % self.path)
return f.getvalue()
def read_task(self, offset, file):
self.server_helper.execute_command("GETFILE %i 0 file=%s" % (offset, quote_path(self.path)), as_user = Users.ADMIN, user_password=self._password, output_handler=file.write)
# this will signal the reader end that there's no more data
file.close()
def start_read_task_from(self, offset):
self._pos = offset
self._queue = multiprocessing.Queue()
self.data = QueueFileMP(self._queue)
self._proc = multiprocessing.Process(target=self.read_task, args=(offset, self.data))
import sys
# restore original stdout file descriptors before forking
stdo, stde, stdi = sys.stdout, sys.stderr, sys.stdin
sys.stdout, sys.stderr, sys.stdin = sys.real_stdout, sys.real_stderr, sys.real_stdin
self._proc.start()
sys.stdout, sys.stderr, sys.stdin = stdo, stde, stdi
def start_read_from(self, offset):
self._pos = offset
f = StringIO.StringIO()
self.server_helper.execute_command("GETFILE %i 0 %s" % (offset, quote_path(self.path)), as_user = Users.ADMIN, user_password=self._password, output_handler=f.write)
self.data = f
self.data.seek(0)
def read(self, count=None):
assert self.data is not None
d = self.data.read(count)
self._pos += len(d)
return d
def readline(self):
assert self.data is not None
d = self.data.readline()
self._pos += len(d)
return d
|