99import os
1010import logging
1111from pathlib import Path
12- from contextlib import ExitStack
12+ try :
13+ from contextlib import ExitStack
14+ except ImportError :
15+ from contextlib2 import ExitStack
1316
1417NAMESPACE_NAMES = frozenset ('mnt ipc net pid user uts' .split ())
1518
1821libc = ctypes .CDLL ('libc.so.6' )
1922
2023
21- def nsfd (process : str , ns_type : str ) -> Path :
24+ def nsfd (process , ns_type ) :
2225 """
2326 Returns the namespace file descriptor for process (self or PID) and namespace type
2427 """
2528 return Path ('/proc' ) / str (process ) / 'ns' / ns_type
29+ nsfd .__annotations__ = {'process' : str , 'ns_type' : str , 'return' : Path }
2630
27-
28- class Namespace :
29- def __init__ (self , pid : str , ns_type : str ):
31+ class Namespace (object ):
32+ def __init__ (self , pid , ns_type ):
3033 self .pid = pid
3134 self .ns_type = ns_type
3235 self .parent_fd = nsfd ('self' , ns_type ).open ()
3336 self .parent_fileno = self .parent_fd .fileno ()
3437 self .target_fd = nsfd (pid , ns_type ).open ()
3538 self .target_fileno = self .target_fd .fileno ()
3639
40+ __init__ .__annotations__ = {'pid' : str , 'ns_type' : str }
41+
3742 def __enter__ (self ):
3843 log .debug ('Entering %s namespace %s' , self .ns_type , self .pid )
3944 libc .setns (self .target_fileno , 0 )
@@ -53,7 +58,7 @@ def main():
5358 parser .add_argument ('--target' , '-t' , required = True , metavar = 'PID' ,
5459 help = 'Specify a target process to get contexts from.' )
5560 for ns in NAMESPACE_NAMES :
56- parser .add_argument ('--{}' .format (ns ), action = 'store_true' , help = 'Enter the {} namespace' .format (ns ))
61+ parser .add_argument ('--{0 }' .format (ns ), action = 'store_true' , help = 'Enter the {0 } namespace' .format (ns ))
5762 parser .add_argument ('--all' , action = 'store_true' , help = 'Enter all namespaces' )
5863 parser .add_argument ('command' , nargs = '*' , default = ['/bin/sh' ])
5964
@@ -68,6 +73,5 @@ def main():
6873 stack .enter_context (ns )
6974 os .execl (args .command [0 ], * args .command )
7075
71-
7276if __name__ == '__main__' :
7377 main ()
0 commit comments