Вызов системного вызова Linux из языка сценариев

Использование только функций POSIX для find также для mv ):

find path_A -name '*AAA*' -exec sh -c 'mv "$@" path_B' find-sh {} +

Дополнительная литература:

15
24.03.2017, 22:58
3 ответа

В Python вы можете использовать модуль ctypes для доступа к произвольным функциям в динамических библиотеках, включая syscall() из libc:

import ctypes

SYS_getrandom = 318 # You need to check the syscall number for your target architecture

libc = ctypes.CDLL(None)
_getrandom_syscall = libc.syscall
_getrandom_syscall.restypes = ctypes.c_int
_getrandom_syscall.argtypes = ctypes.c_int, ctypes.POINTER(ctypes.c_char), ctypes.c_size_t, ctypes.c_uint

def getrandom(size, flags=0):
    buf = (ctypes.c_char * size)()
    result = _getrandom_syscall(SYS_getrandom, buf, size, flags)
    if result < 0:
        raise OSError(ctypes.get_errno(), 'getrandom() failed')
    return bytes(buf)

Если ваша libc включает функцию-обертку getrandom(), вы можете вызвать и ее:

import ctypes

libc = ctypes.CDLL(None)
_getrandom = libc.getrandom
_getrandom.restypes = ctypes.c_int
_getrandom.argtypes = ctypes.POINTER(ctypes.c_char), ctypes.c_size_t, ctypes.c_uint

def getrandom(size, flags=0):
    buf = (ctypes.c_char * size)()
    result = _getrandom(buf, size, flags)
    if result < 0:
        raise OSError(ctypes.get_errno(), 'getrandom() failed')
    return bytes(buf)
28
27.01.2020, 19:49

Perl позволяет это с помощью функции системного вызова :

$ perldoc -f syscall
    syscall NUMBER, LIST
            Calls the system call specified as the first element of the list,
            passing the remaining elements as arguments to the system call. If
⋮

В документации также есть пример вызова write (2):

require 'syscall.ph';        # may need to run h2ph
my $s = "hi there\n";
syscall(SYS_write(), fileno(STDOUT), $s, length $s);

Не могу сказать, что я когда-либо использовал эту функцию. Что ж, до того, как только сейчас подтвердить, что пример действительно работает.

Похоже, это работает с getrandom :

$ perl -E 'require "syscall.ph"; $v = " "x8; syscall(SYS_getrandom(), $v, length $v, 0); print $v' | xxd
00000000: 5790 8a6d 714f 8dbe                      W..mqO..

И если у вас нет getrandom в вашем syscall.ph, вы можете использовать вместо этого номер. Это 318 на моем тестовом Debian (amd64). Помните, что номера системных вызовов Linux зависят от архитектуры.

33
27.01.2020, 19:49

В Ruby есть функция syscall(num [, args...]) → integer.

Например:

irb(main):010:0> syscall 1, 1, "hello\n", 6
hello
=> 6

С getrandom():

irb(main):001:0> a = "aaaaaaaa"
=> "aaaaaaaa"
irb(main):002:0> syscall 318,a,8,0
=> 8
irb(main):003:0> a
=> "\x9Cq\xBE\xD6|\x87\u0016\xC6"
irb(main):004:0> 
17
27.01.2020, 19:49

Теги

Похожие вопросы