def terminate(self):
try:
os.kill(self.pid, signal.SIGTERM)
except OSError, e:
if e.errno == errno.ESRCH:
return # process already killed by someone else
if e.errno == errno.EPERM:
# this can only happen if the original session was started as
# a different user. e.g. if the broker has been restarted with
# --demote=<some other user>. but don't worry too much about it
# as sessions are eventually terminated anyway.
print(
'WARNING: session with PID=%d not terminated because it '
'is owned by a different user. did you restart a broker '
'as a different user?' % self.pid
)
return
raise e
python类EPERM的实例源码
def _copyxattr(src, dst, *, follow_symlinks=True):
"""Copy extended filesystem attributes from `src` to `dst`.
Overwrite existing attributes.
If `follow_symlinks` is false, symlinks won't be followed.
"""
try:
names = os.listxattr(src, follow_symlinks=follow_symlinks)
except OSError as e:
if e.errno not in (errno.ENOTSUP, errno.ENODATA):
raise
return
for name in names:
try:
value = os.getxattr(src, name, follow_symlinks=follow_symlinks)
os.setxattr(dst, name, value, follow_symlinks=follow_symlinks)
except OSError as e:
if e.errno not in (errno.EPERM, errno.ENOTSUP, errno.ENODATA):
raise
def test_track_cannot_read(no_sleep, mock_mainfunc, ptmpdir):
_, _, inotifier = mock_mainfunc
def add_watch(*args, **kwargs):
exc = IOError("Hello?")
exc.errno = errno.EPERM
raise exc
inotifier.add_watch.side_effect = add_watch
app = get_app()
app.destination_path = ptmpdir.join("filename").strpath
with pytest.raises(IOError):
app.track()
def terminate(self):
try:
os.kill(self.pid, signal.SIGTERM)
except OSError, e:
if e.errno == errno.ESRCH:
return # process already killed by someone else
if e.errno == errno.EPERM:
# this can only happen if the original session was started as
# a different user. e.g. if the broker has been restarted with
# --demote=<some other user>. but don't worry too much about it
# as sessions are eventually terminated anyway.
print(
'WARNING: session with PID=%d not terminated because it '
'is owned by a different user. did you restart a broker '
'as a different user?' % self.pid
)
return
raise e
def live(self):
if not self.proc_path:
return
self.info("Proc path: %s" % self.proc_path)
key = choice(self.proc_keys)
filename = path_join(self.proc_path, key)
data = self.generator.createValue()
self.info("Write data in %s: (len=%s) %r"
% (filename, len(data), data))
try:
output = open(filename, 'w')
output.write(data)
output.close()
except IOError, err:
if err.errno in (EINVAL, EPERM):
pass
elif err.errno in (ENOENT, EACCES):
self.error("Unable to write %s: %s" % (filename, err))
self.removeKey(key)
else:
raise
def queryWirelessDevice(self,iface):
try:
from pythonwifi.iwlibs import Wireless
import errno
except ImportError:
return False
else:
try:
ifobj = Wireless(iface) # a Wireless NIC Object
wlanresponse = ifobj.getAPaddr()
except IOError, (error_no, error_str):
if error_no in (errno.EOPNOTSUPP, errno.ENODEV, errno.EPERM):
return False
else:
print "error: ",error_no,error_str
return True
else:
return True
def queryWirelessDevice(self,iface):
try:
from pythonwifi.iwlibs import Wireless
import errno
except ImportError:
return False
else:
try:
ifobj = Wireless(iface) # a Wireless NIC Object
wlanresponse = ifobj.getAPaddr()
except IOError, (error_no, error_str):
if error_no in (errno.EOPNOTSUPP, errno.ENODEV, errno.EPERM):
return False
else:
print "error: ",error_no,error_str
return True
else:
return True
def graph(self, uuid=None, hook=True, ctx=None, user=None, roles=None, **kwargs):
if uuid is None and kwargs.get('create', False):
uuid = uuidgen()
for k,v in self.graph_opts.iteritems():
if k not in kwargs:
kwargs[k] = v
if hook:
kwargs['hooks'] = CollectionHooks(uuid, self)
try:
g = Graph(self.graph_path(uuid), **kwargs)
except:
self.remove(uuid) if ctx is None else ctx.remove(uuid)
raise
if user is not None:
# new graph - do not check creds
if g.updated:
pass
else:
if not self.user_allowed(g, user, roles):
g.close()
raise OSError(errno.EPERM, 'Permission denied', uuid)
return g
def get_all_inodes(self):
inodes = {}
for pid in pids():
try:
inodes.update(self.get_proc_inodes(pid))
except OSError as err:
# os.listdir() is gonna raise a lot of access denied
# exceptions in case of unprivileged user; that's fine
# as we'll just end up returning a connection with PID
# and fd set to None anyway.
# Both netstat -an and lsof does the same so it's
# unlikely we can do any better.
# ENOENT just means a PID disappeared on us.
if err.errno not in (
errno.ENOENT, errno.ESRCH, errno.EPERM, errno.EACCES):
raise
return inodes
def wrap_exceptions(fun):
"""Decorator which translates bare OSError and IOError exceptions
into NoSuchProcess and AccessDenied.
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except EnvironmentError as err:
# ENOENT (no such file or directory) gets raised on open().
# ESRCH (no such process) can get raised on read() if
# process is gone in meantime.
if err.errno in (errno.ENOENT, errno.ESRCH):
raise NoSuchProcess(self.pid, self._name)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
return wrapper
def exe(self):
try:
return readlink("%s/%s/exe" % (self._procfs_path, self.pid))
except OSError as err:
if err.errno in (errno.ENOENT, errno.ESRCH):
# no such file error; might be raised also if the
# path actually exists for system processes with
# low pids (about 0-20)
if os.path.lexists("%s/%s" % (self._procfs_path, self.pid)):
return ""
else:
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
else:
raise ZombieProcess(self.pid, self._name, self._ppid)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
def wrap_exceptions(fun):
"""Decorator which translates bare OSError exceptions into
NoSuchProcess and AccessDenied.
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except OSError as err:
if err.errno == errno.ESRCH:
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
else:
raise ZombieProcess(self.pid, self._name, self._ppid)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
return wrapper
def wrap_exceptions(fun):
"""Decorator which translates bare OSError exceptions into
NoSuchProcess and AccessDenied.
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except OSError as err:
if err.errno == errno.ESRCH:
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
else:
raise ZombieProcess(self.pid, self._name, self._ppid)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
return wrapper
def _send_signal(self, sig):
if self.pid == 0:
# see "man 2 kill"
raise ValueError(
"preventing sending signal to process with PID 0 as it "
"would affect every process in the process group of the "
"calling process (os.getpid()) instead of PID 0")
try:
os.kill(self.pid, sig)
except OSError as err:
if err.errno == errno.ESRCH:
if OPENBSD and pid_exists(self.pid):
# We do this because os.kill() lies in case of
# zombie processes.
raise ZombieProcess(self.pid, self._name, self._ppid)
else:
self._gone = True
raise NoSuchProcess(self.pid, self._name)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
def wrap_exceptions(fun):
"""Call callable into a try/except clause and translate ENOENT,
EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
"""
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except EnvironmentError as err:
# ENOENT (no such file or directory) gets raised on open().
# ESRCH (no such process) can get raised on read() if
# process is gone in meantime.
if err.errno in (errno.ENOENT, errno.ESRCH):
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
else:
raise ZombieProcess(self.pid, self._name, self._ppid)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
return wrapper
def wrap_exceptions(fun):
"""Decorator which translates bare OSError and IOError exceptions
into NoSuchProcess and AccessDenied.
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except EnvironmentError as err:
# ENOENT (no such file or directory) gets raised on open().
# ESRCH (no such process) can get raised on read() if
# process is gone in meantime.
if err.errno in (errno.ENOENT, errno.ESRCH):
raise NoSuchProcess(self.pid, self._name)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
return wrapper
def exe(self):
try:
return readlink("%s/%s/exe" % (self._procfs_path, self.pid))
except OSError as err:
if err.errno in (errno.ENOENT, errno.ESRCH):
# no such file error; might be raised also if the
# path actually exists for system processes with
# low pids (about 0-20)
if os.path.lexists("%s/%s" % (self._procfs_path, self.pid)):
return ""
else:
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
else:
raise ZombieProcess(self.pid, self._name, self._ppid)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
def wrap_exceptions(fun):
"""Decorator which translates bare OSError exceptions into
NoSuchProcess and AccessDenied.
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except OSError as err:
if err.errno == errno.ESRCH:
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
else:
raise ZombieProcess(self.pid, self._name, self._ppid)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
return wrapper
def wrap_exceptions(fun):
"""Decorator which translates bare OSError exceptions into
NoSuchProcess and AccessDenied.
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except OSError as err:
if err.errno == errno.ESRCH:
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
else:
raise ZombieProcess(self.pid, self._name, self._ppid)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
return wrapper
def _send_signal(self, sig):
if self.pid == 0:
# see "man 2 kill"
raise ValueError(
"preventing sending signal to process with PID 0 as it "
"would affect every process in the process group of the "
"calling process (os.getpid()) instead of PID 0")
try:
os.kill(self.pid, sig)
except OSError as err:
if err.errno == errno.ESRCH:
if OPENBSD and pid_exists(self.pid):
# We do this because os.kill() lies in case of
# zombie processes.
raise ZombieProcess(self.pid, self._name, self._ppid)
else:
self._gone = True
raise NoSuchProcess(self.pid, self._name)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
def wrap_exceptions(fun):
"""Call callable into a try/except clause and translate ENOENT,
EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
"""
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except EnvironmentError as err:
# ENOENT (no such file or directory) gets raised on open().
# ESRCH (no such process) can get raised on read() if
# process is gone in meantime.
if err.errno in (errno.ENOENT, errno.ESRCH):
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
else:
raise ZombieProcess(self.pid, self._name, self._ppid)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
return wrapper
def _copyxattr(src, dst, *, follow_symlinks=True):
"""Copy extended filesystem attributes from `src` to `dst`.
Overwrite existing attributes.
If `follow_symlinks` is false, symlinks won't be followed.
"""
try:
names = os.listxattr(src, follow_symlinks=follow_symlinks)
except OSError as e:
if e.errno not in (errno.ENOTSUP, errno.ENODATA):
raise
return
for name in names:
try:
value = os.getxattr(src, name, follow_symlinks=follow_symlinks)
os.setxattr(dst, name, value, follow_symlinks=follow_symlinks)
except OSError as e:
if e.errno not in (errno.EPERM, errno.ENOTSUP, errno.ENODATA):
raise
def _try_except_permissionerror_iter(try_iter, except_iter):
if sys.version_info >= (3, 3):
try:
for x in try_iter():
yield x
except PermissionError as exc:
for x in except_iter(exc):
yield x
else:
try:
for x in try_iter():
yield x
except EnvironmentError as exc:
if exc.errno not in (EPERM, EACCES):
raise
else:
for x in except_iter(exc):
yield x
def set_file_utime(filename, desired_time):
"""
Set the utime of a file, and if it fails, raise a more explicit error.
:param filename: the file to modify
:param desired_time: the epoch timestamp to set for atime and mtime.
:raises: SetFileUtimeError: if you do not have permission (errno 1)
:raises: OSError: for all errors other than errno 1
"""
try:
os.utime(filename, (desired_time, desired_time))
except OSError as e:
# Only raise a more explicit exception when it is a permission issue.
if e.errno != errno.EPERM:
raise e
raise SetFileUtimeError(
("The file was downloaded, but attempting to modify the "
"utime of the file failed. Is the file owned by another user?"))
def scan_and_print_neighbors(net, interface, timeout=1):
global ips_o
print_fmt("\n\033[94m[ARP]\033[0m %s sur %s" % (net, interface))
try:
ans, unans = scapy.layers.l2.arping(net, iface=interface, timeout=timeout, verbose=False)
for s, r in ans.res:
line = r.sprintf("%Ether.src% %ARP.psrc%")
ips_o.append(line.split(' ')[2])
line = mac_address_id(line)
try:
hostname = socket.gethostbyaddr(r.psrc)
line += " " + hostname[0]
except socket.herror:
pass
except KeyboardInterrupt:
print '\033[91m[-]\033[0m L\'utilisateur a choisi l\'interruption du process.'
break
logger.info("\033[96m[ONLINE]\033[0m " + line)
except socket.error as e:
if e.errno == errno.EPERM:
logger.error("\033[91m[-]\033[0m %s. Vous n'etes pas root?", e.strerror)
else:
raise
def checkhost(ip):
global ips_o
conf.verb = 0
try:
ping, no = sr(IP(dst=ip)/ICMP(), timeout=1.5, retry=-2)
if ping.res:
logger.info("\033[96m[ONLINE]\033[0m Cible: " + ip)
ips_o.append(ip)
except socket.error as e:
if e.errno == errno.EPERM:
logger.error("\033[91m[-]\033[0m %s. Vous n'etes pas root?", e.strerror)
else:
pass
except Exception as e:
logger.error("\033[91m[-]\033[0m Erreur Checkhost() --> {}.".format(e.__class__))
pass
def get_all_inodes(self):
inodes = {}
for pid in pids():
try:
inodes.update(self.get_proc_inodes(pid))
except OSError as err:
# os.listdir() is gonna raise a lot of access denied
# exceptions in case of unprivileged user; that's fine
# as we'll just end up returning a connection with PID
# and fd set to None anyway.
# Both netstat -an and lsof does the same so it's
# unlikely we can do any better.
# ENOENT just means a PID disappeared on us.
if err.errno not in (
errno.ENOENT, errno.ESRCH, errno.EPERM, errno.EACCES):
raise
return inodes
def wrap_exceptions(fun):
"""Decorator which translates bare OSError and IOError exceptions
into NoSuchProcess and AccessDenied.
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except EnvironmentError as err:
# ENOENT (no such file or directory) gets raised on open().
# ESRCH (no such process) can get raised on read() if
# process is gone in meantime.
if err.errno in (errno.ENOENT, errno.ESRCH):
raise NoSuchProcess(self.pid, self._name)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
return wrapper
def exe(self):
try:
return readlink("%s/%s/exe" % (self._procfs_path, self.pid))
except OSError as err:
if err.errno in (errno.ENOENT, errno.ESRCH):
# no such file error; might be raised also if the
# path actually exists for system processes with
# low pids (about 0-20)
if os.path.lexists("%s/%s" % (self._procfs_path, self.pid)):
return ""
else:
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
else:
raise ZombieProcess(self.pid, self._name, self._ppid)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
def wrap_exceptions(fun):
"""Decorator which translates bare OSError exceptions into
NoSuchProcess and AccessDenied.
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
except OSError as err:
if err.errno == errno.ESRCH:
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._name)
else:
raise ZombieProcess(self.pid, self._name, self._ppid)
if err.errno in (errno.EPERM, errno.EACCES):
raise AccessDenied(self.pid, self._name)
raise
return wrapper