Page 1 of 1

Disk image tools

PostPosted: Fri, 22.11.2013 00:03:56
by ZEK
Утилита для создания RAW образов дисков
Для работы утилиты нужен .NET Framework 2.0 (входит в состав дотнетов 3.0 3.5)
Для скриптинга используется язык сценариев Lua, расширенный через LuaInterface до возможности работы с дотнетом
В глобальную область видимости добавленные несколько функций для работы с дотнетом
import "Namespace" - импорт дотнетовского пространства имен, по умолчанию всегда импортируются System, System.IO, System.Collection
each(IEnumerable) - посредник между дотнетовскими коллекциями и Lua, нужен для обхода циклом массивов и коллекций возвращаемых расширением Lua



командная строка
ImgTool scriptFile imgFile

scriptFile - имя файла с скриптом lua
imgFile - имя файла образа

Для создания образа необходимо написать скрипт на Lua, в глобальную область видимости добавлены следующие функции
img_exists() - возвращает true если образ существует
img_drop() - удаляет файл образа
img_create(int size) - создает пустой не форматированный файл образа, size - размер образа в mb, размер должен быть не менее 5мб
img_open() - открывает образ
get_extfs() - возвращает контекст нативной файловой системы
copy(inStream, outStream) - копирует полностью входящий поток в исходящий

img_create, img_open возвращают контекст образа ImageFile


Функции предоставляемые контекстом ImageFile
:Open() - открывает файл образа и возвращает контекст файловой системы первого раздела, открыть можно только форматированный раздел
:Format(string label) - форматирует диск образа, если размер образа больше 512мб, файловая система будет FAT32, label - метка тома, создается MBR и один раздел на весь диск


глобальная функция get_extfs и ImageFile:Open возвращают контекст файловой системы DiskFileSystem, предоставляют одинаковые функции

Описание функций контекста файловой системы
Code: Select all
        // Скопировать файл в пределах файловой системы, параметр overwrite не обязательный, по умолчанию false
        :CopyFile(string sourceFile, string destinationFile[, bool overwrite]);

        // Создать каталог
        :CreateDirectory(string path);

        // Удалить каталог, параметр recursive не обязательный, по умолчанию false
        :DeleteDirectory(string path[, bool recursive]);

        // Удалить файл
        :DeleteFile(string path);

        // Проверить существование каталога, возвращает true если существует
        bool DirectoryExists(string path);

        // Проверить существование файла, возвращает true если существует
        bool FileExists(string path);

        // Проверить существование файла или каталога, true если существует
        bool Exists(string path);

        // Вернуть список каталогов по заданному пути, возвращает массив строк с именами каталогов
        // необязательный параметр searchPattern задает маску для списка каталогов
        // необязательный параметр searchOption задает параметры поиска каталогов
        string[] GetDirectories(string path [[, string searchPattern], SearchOption searchOption] );

        // Вернуть список файлов по заданному пути, возвращает массив строк с именами файлов
        // необязательный параметр searchPattern задает маску для списка файлов
        // необязательный параметр searchOption задает параметры поиска файлов
        string[] GetFiles(string path [[, string searchPattern],SearchOption searchOption] );

        // Вернуть список файлов и подкаталогов для заданного пути, возвращает массив строк с именами каталогов и файлов
        // Необязательный параметр searchPattern задает маску для списка
        string[] GetFileSystemEntries(string path [, string searchPattern] );

        // Переместить каталог
        :MoveDirectory(string sourceDirectoryName, string destinationDirectoryName);

        // Переместить файл
        // необязательный параметр overwrite указывает необходимость перезаписи файла, по умолчанию false
        :MoveFile(string sourceName, string destinationName [, bool overwrite] );

        // Открыть файл
        // параметр FileMode задает режим открытия (FileMode.Open, FileMode.Create, FileMode.CreateNew, FileMode.Append)
        // необязательный параметр access задает режим доступа к файлу
        SparseStream OpenFile(string path, FileMode mode [, FileAccess access] )

        /// <summary>
        /// Gets the attributes of a file or directory.
        /// </summary>
        /// <param name="path">The file or directory to inspect</param>
        /// <returns>The attributes of the file or directory</returns>
        FileAttributes GetAttributes(string path);

        /// <summary>
        /// Sets the attributes of a file or directory.
        /// </summary>
        /// <param name="path">The file or directory to change</param>
        /// <param name="newValue">The new attributes of the file or directory</param>
        void SetAttributes(string path, FileAttributes newValue);

        /// <summary>
        /// Gets the creation time (in local time) of a file or directory.
        /// </summary>
        /// <param name="path">The path of the file or directory</param>
        /// <returns>The creation time.</returns>
        DateTime GetCreationTime(string path);

        /// <summary>
        /// Sets the creation time (in local time) of a file or directory.
        /// </summary>
        /// <param name="path">The path of the file or directory.</param>
        /// <param name="newTime">The new time to set.</param>
        void SetCreationTime(string path, DateTime newTime);

        /// <summary>
        /// Gets the creation time (in UTC) of a file or directory.
        /// </summary>
        /// <param name="path">The path of the file or directory.</param>
        /// <returns>The creation time.</returns>
        DateTime GetCreationTimeUtc(string path);

        /// <summary>
        /// Sets the creation time (in UTC) of a file or directory.
        /// </summary>
        /// <param name="path">The path of the file or directory.</param>
        /// <param name="newTime">The new time to set.</param>
        void SetCreationTimeUtc(string path, DateTime newTime);

        /// <summary>
        /// Gets the last access time (in local time) of a file or directory.
        /// </summary>
        /// <param name="path">The path of the file or directory</param>
        /// <returns>The last access time</returns>
        DateTime GetLastAccessTime(string path);

        /// <summary>
        /// Sets the last access time (in local time) of a file or directory.
        /// </summary>
        /// <param name="path">The path of the file or directory.</param>
        /// <param name="newTime">The new time to set.</param>
        void SetLastAccessTime(string path, DateTime newTime);

        /// <summary>
        /// Gets the last access time (in UTC) of a file or directory.
        /// </summary>
        /// <param name="path">The path of the file or directory</param>
        /// <returns>The last access time</returns>
        DateTime GetLastAccessTimeUtc(string path);

        /// <summary>
        /// Sets the last access time (in UTC) of a file or directory.
        /// </summary>
        /// <param name="path">The path of the file or directory.</param>
        /// <param name="newTime">The new time to set.</param>
        void SetLastAccessTimeUtc(string path, DateTime newTime);

        /// <summary>
        /// Gets the last modification time (in local time) of a file or directory.
        /// </summary>
        /// <param name="path">The path of the file or directory</param>
        /// <returns>The last write time</returns>
        DateTime GetLastWriteTime(string path);

        /// <summary>
        /// Sets the last modification time (in local time) of a file or directory.
        /// </summary>
        /// <param name="path">The path of the file or directory.</param>
        /// <param name="newTime">The new time to set.</param>
        void SetLastWriteTime(string path, DateTime newTime);

        /// <summary>
        /// Gets the last modification time (in UTC) of a file or directory.
        /// </summary>
        /// <param name="path">The path of the file or directory</param>
        /// <returns>The last write time</returns>
        DateTime GetLastWriteTimeUtc(string path);

        /// <summary>
        /// Sets the last modification time (in UTC) of a file or directory.
        /// </summary>
        /// <param name="path">The path of the file or directory.</param>
        /// <param name="newTime">The new time to set.</param>
        void SetLastWriteTimeUtc(string path, DateTime newTime);

        /// <summary>
        /// Gets the length of a file.
        /// </summary>
        /// <param name="path">The path to the file</param>
        /// <returns>The length in bytes</returns>
        long GetFileLength(string path);

        /// <summary>
        /// Gets an object representing a possible file.
        /// </summary>
        /// <param name="path">The file path</param>
        /// <returns>The representing object</returns>
        /// <remarks>The file does not need to exist</remarks>
        DiscFileInfo GetFileInfo(string path);

        /// <summary>
        /// Gets an object representing a possible directory.
        /// </summary>
        /// <param name="path">The directory path</param>
        /// <returns>The representing object</returns>
        /// <remarks>The directory does not need to exist</remarks>
        DiscDirectoryInfo GetDirectoryInfo(string path);

        /// <summary>
        /// Gets an object representing a possible file system object (file or directory).
        /// </summary>
        /// <param name="path">The file system path</param>
        /// <returns>The representing object</returns>
        /// <remarks>The file system object does not need to exist</remarks>
        DiscFileSystemInfo GetFileSystemInfo(string path);

Re: Disk image tools

PostPosted: Fri, 22.11.2013 04:17:09
by TS-Labs
Круто. А теперечи б еще:
1. Чем собирается?
2. Где скочять собранную тулзу без СМС чтоб ей кормить командлайн и иметь на выходе имедж?

Re: Disk image tools

PostPosted: Fri, 22.11.2013 14:02:25
by ZEK
Допилить надо, там чуть что вместо ошибки на синтаксис или еще что сразу exception я пока не замарачивался с проверками, ток 3 часа потратил, это альфа макет

Re: Disk image tools

PostPosted: Wed, 27.11.2013 20:51:00
by ZEK
В архиве, тулса и пример
скритить на lua

Code: Select all

import "System"
import "System.IO"
import "DiscUtils"

function dir(fs)

   for d in each(fs:GetDirectories("")) do
      print(d)
   end   

   for d in each(fs:GetFiles("")) do
      print(d)
   end   

   print("------")
end

if img_exists() then
   img = img_open()
else
   img = img_create(5)
   img:Format("label1") -- если размер образа больше 512мб, то будет FAT32
end

intfs = img:Open()
extfs = get_extfs(false) -- параметр - только для чтения


intfs:CreateDirectory("TEST")
intfs:CreateDirectory("TEST1")
intfs:CreateDirectory("TEST2")

dir(intfs)

intfs:DeleteDirectory("TEST1", false)

dir(intfs)

dir(extfs)


from = extfs:OpenFile("test.zip", FileMode.Open)
to = intfs:OpenFile("TEST2\\test.zip", FileMode.Create)

copy(from, to)



---

Надо в какой нить редактор интелисенс прикрутить с подсказкой, функций дофига

Re: Disk image tools

PostPosted: Mon, 21.07.2014 19:15:00
by ZEK
Версия 2, лайт эдишн

Юзать можно 2мя способоами
1. imgmake copy src dst file.img копирует Src в Dst который в образе file.img
2. imgmake config_file читает скрпитик из набора команд copy, пример в архиве


Ахтунг, пороверок всяких лень было делать, поэтому будет безбожно матюкаться если нет файла источника итд
если кто будет юзать, тогда есть смысл дотачивать, а така закинуть wc или еще какой нить каталог в файл образа, вполне покатит

Re: Disk image tools

PostPosted: Tue, 22.07.2014 11:51:21
by TS-Labs
Проверил, работает.

Re: Disk image tools

PostPosted: Tue, 22.07.2014 14:18:19
by LessNick
Image

Так что оно в конечном итоге делает? Образ HDD для Unreal? Или это просто либа?

Re: Disk image tools

PostPosted: Tue, 22.07.2014 14:19:28
by ZEK
Утилита в образ винта позволяет из командной строки накидать файлов и каталогов

Re: Disk image tools

PostPosted: Tue, 22.07.2014 16:15:41
by LessNick
ZEK wrote:Утилита в образ винта позволяет из командной строки накидать файлов и каталогов


Хм… ну я когда-то давно писал, что есть «бесплатная» тулза от VMWare для монтирования образа как диск на пэцэте под вендой.

«Unreal Speccy + HDD: Работа с файлами»

Re: Disk image tools

PostPosted: Tue, 22.07.2014 16:30:45
by ZEK
жестко диск подключать, но я как бы не заставляю

Re: Disk image tools

PostPosted: Sat, 23.07.2016 08:01:22
by TS-Labs
Очень кратенько, потому что чукча не писатель.
Нашел такую свалку утилит.

Результаты RnD следующие.
0. Стояла задача удалять и копировать файлы в имедж анрыльного винта при помощи батника.
1. Протестировал конкретно тулзы imgcpy.exe и mdel.exe.
2. mdel.exe неюзабельна, потому что автор долбоеб.
Во1х, не понимает имедж с MBR, во2х когда удалить мбр, то понимает, но указанный файл все равно не находит. Дальше я заебся в ней рыться и списал фтопку. Удаление файла нам не далось.
3. imgcpy.exe имеет авторство более продвинутого автора, поэтому юзабельна. Прекрасно понимает имедж из анрыла, позволяет создавать папки и копировать туда файл. Удаление старой версии файла при перезаписи не требуется.
4. Формат пути для мбр-ных имеджей начинается с буквы диска, которая для 1-го раздела с:\ и так далее.
Создать папку:
imgcpy wc.img=c:\new_papka
Скопирожать файл:
imgcpy file.txt wc.img=c:\my_filename.txt
5. Для imgcpy имеется замечательный сорец, скомпилить который я не пробовал, но зато пробовал найти хедер "FAT.h", содержащий меганажористые функции для работы с фатами в имедже. Что-то нашлось, но какое-то оно стремное...

Re: Disk image tools

PostPosted: Sat, 23.07.2016 12:52:31
by psb
я юзал mtools - работало.

Re: Disk image tools

PostPosted: Sat, 23.07.2016 13:53:34
by DimkaM
mtools да подтверждаю, очень юзабельна.

Если уж нужно что то специфичное, то я цеплял dllку diskutils в vs

Re: Disk image tools

PostPosted: Sat, 23.07.2016 14:59:07
by psb
а дллку откуда? а то может приделать к анрилу чтобы он папку в образ собирал при запуске?

Re: Disk image tools

PostPosted: Sat, 23.07.2016 15:04:33
by DimkaM
Хз в инетах нашол. DiskUtils.dll
Она дотнетовая, я хз как она прикрутитсяли к Сям

Re: Disk image tools

PostPosted: Sat, 23.07.2016 15:08:24
by DimkaM

Re: Disk image tools

PostPosted: Sat, 23.07.2016 20:23:13
by psb
в топку дотнет.

Re: Disk image tools

PostPosted: Sat, 23.07.2016 21:09:41
by DimkaM
Ну mtools тогда, и прикручивать ничего не надо, батником вполне можно рекурсию устроить по закидыванию файлов

Re: Disk image tools

PostPosted: Wed, 26.07.2017 03:56:08
by TS-Labs
TS-Labs wrote:imgcpy.exe имеет авторство более продвинутого автора

... у которого мсдос гойловного мозга, поэтому утилита не понимает длинных путей и брякается в рандомнейших местах. Попытки пересобрать оную из сорцов были безвременно брошены (сорцы под борланд).